﻿Imports System.Globalization

Partial Public Class frm_VesselOnPort
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData()
    Dim clsFc As New ClassFunction
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "ACTUAL "
            LoadBOoking()
            txtBooking_no.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearch.ClientID + "')")
            txtShipName.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearch.ClientID + "')")
        End If
    End Sub

    Private Sub LoadBOoking()
        PanelBookingItem.Visible = True
        PanelOperation.Visible = False
        ' Dim ds As DataSet = clsGet.Get_Booking("", "", "", "'OA','FN'", True, "")
        ViewState("Booking_OLD") = ""
        Dim ds As DataSet = clsGet.Get_BookingMarketing("", "'OA','FN'", True, "", "0", "", "0", "", "", "")
        If (ds.Tables(0).Rows.Count > 0) Then
            ViewState("Operation") = ds
            gridItem.DataSource = ViewState("Operation")
            gridItem.DataBind()
        Else
            gridItem.DataSource = Nothing
            gridItem.DataBind()
            lbAlert.Text = "ไม่พบรายการ Booking"
        End If
    End Sub

    Public Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
        ViewState("Booking_OLD") = ""
        Dim CurrentIndex As Integer = gridItem.PageIndex
        Select Case e.CommandArgument.ToString().ToLower()
            Case "first"
                gridItem.PageIndex = 0
            Case "prev"
                If (gridItem.PageIndex <> 0) Then
                    gridItem.PageIndex = CurrentIndex - 1
                End If
            Case "next"
                If (gridItem.PageIndex <> gridItem.PageCount) Then
                    gridItem.PageIndex = CurrentIndex + 1
                End If
            Case "last"
                gridItem.PageIndex = gridItem.PageCount
        End Select
        gridItem.DataSource = ViewState("Operation")
        gridItem.DataBind()
    End Sub

    Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        ViewState("Booking_OLD") = ""
        Dim Page As GridViewRow = gridItem.BottomPagerRow
        Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
        gridItem.PageIndex = ddlPage.SelectedIndex
        gridItem.DataSource = ViewState("Operation")
        gridItem.DataBind()
    End Sub

    Private Sub gridItem_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridItem.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        rowDueDate.Visible = False
        rowBillingDate.Visible = False
        txtDueDate.Text = String.Empty
        txtDate.Text = String.Empty
        If (gridItem.PageIndex <> 0) Then
            Index = Index Mod (gridItem.PageIndex * 10)
        End If
        If e.CommandName = "Edit" Then
            ViewState("IND") = Index
            txtid.Text = String.Empty
            txtBillTo.Text = String.Empty
            lbNet.Text = "0"
            ViewState("EditBooking") = gridItem.DataKeys(Index).Values("Booking_no")
            Dim ChkBarge As Boolean = False
            Dim ChkOther As Boolean = False
            If (ViewState("EditBooking").ToString.Substring(0, 1) = "B") Then
                ChkBarge = True
            ElseIf (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
                ChkOther = True
            End If
            If (ChkBarge) Then
                'Barge
                If (gridItem.DataKeys(Index).Values("Status") & "" = "F") Then
                    btnSave.Visible = False
                    btnPrintCNDN.Visible = False
                    btnComplete.Visible = False
                Else
                    btnSave.Visible = True
                    btnPrintCNDN.Visible = False
                End If
                Dim dtberge As DataTable = clsGet.Get_Bas_Vessel_In(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1))
                Dim StartDate As String = ""
                Dim EndDate As String = ""
                If (dtberge.Rows.Count > 0) Then
                    StartDate = dtberge.Rows(0).Item("StartDate")
                    EndDate = dtberge.Rows(0).Item("EndDate")
                    For Each dd As DataRow In dtberge.Rows
                        Try
                            If (CDate(ClassFunctionGetData.CDateT(StartDate)) > CDate(ClassFunctionGetData.CDateT(dd.Item("StartDate")))) Then
                                StartDate = dd.Item("StartDate")
                            End If
                        Catch ex As Exception

                        End Try
                        Try
                            If (CDate(ClassFunctionGetData.CDateT(EndDate)) < CDate(ClassFunctionGetData.CDateT(dd.Item("EndDate")))) Then
                                EndDate = dd.Item("EndDate")
                            End If
                        Catch ex As Exception

                        End Try
                    Next
                End If

                lbBerth.Text = StartDate & " - " & EndDate
                rowSoldTo.Visible = True
                rowBillTo.Visible = True
                ViewState("Payin") = "1"
                ViewState("PORT") = "B"
                ViewState("Plant") = "1104"
                ViewState("Vehicle_Text") = "Barge Vessel"
                Dim dtMat As DataTable = SetStructure(dtMat)
                AddBargeMaterial(dtMat)


                Dim c As Integer = 0
                Dim dtT As DataTable = dtMat.Copy
                For i As Integer = 0 To dtMat.Rows.Count - 1
                    If (dtMat.Rows(i).Item("data4") & "" = "0.00") Then
                        dtT.Rows(i - c).Delete()
                        dtT.AcceptChanges()
                        c += 1
                    End If
                Next
                dtMat = dtT

                ViewState("dtMat") = dtMat

                GridMat.DataSource = dtMat
                GridMat.DataBind()

                gridTariff.DataSource = dtMat
                gridTariff.DataBind()
            ElseIf (ChkOther) Then
                'OTHer Service
                If (gridItem.DataKeys(Index).Values("Status") & "" = "F") Then
                    btnSave.Visible = False
                    btnPrintCNDN.Visible = False
                    btnComplete.Visible = False
                Else
                    btnSave.Visible = True
                    btnPrintCNDN.Visible = False
                End If

                ViewState("Payin") = "1"
                ViewState("PORT") = "B"
                ViewState("Plant") = "1104"
                Dim dtOther As DataTable = clsGet.Get_OtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1))
                ViewState("SoldTo") = dtOther.Rows(0).Item("Customer_no")
                ViewState("SoldTo_Name") = dtOther.Rows(0).Item("Customer_name")
                ViewState("BillTo") = dtOther.Rows(0).Item("Bill_To_no")

                If (dtOther.Rows(0).Item("Booking_no") & "" <> "") Then
                    dtOther = clsGet.Get_BookingOneRecord(dtOther.Rows(0).Item("Booking_no") & "").Tables(0)
                    ViewState("Vehicle_Text") = dtOther.Rows(0).Item("Vehicle_Text") & ""
                End If

                Dim dtMat As DataTable = SetStructure(dtMat)
                AddOtherService(dtMat)

                Dim c As Integer = 0
                Dim dtT As DataTable = dtMat.Copy
                For i As Integer = 0 To dtMat.Rows.Count - 1
                    If (dtMat.Rows(i).Item("data4") & "" = "0.00") Then
                        dtT.Rows(i - c).Delete()
                        dtT.AcceptChanges()
                        c += 1
                    End If
                Next
                dtMat = dtT

                ViewState("dtMat") = dtMat

                GridMat.DataSource = dtMat
                GridMat.DataBind()

                gridTariff.DataSource = dtMat
                gridTariff.DataBind()
            Else
                'Booking Normal
                If (gridItem.DataKeys(Index).Values("Payin") & "" = "0") Then
                    rowDueDate.Visible = True
                    rowBillingDate.Visible = False
                Else
                    rowDueDate.Visible = False
                    rowBillingDate.Visible = True
                End If
                btnSave.Visible = True
                btnPrintCNDN.Visible = True
                rowSoldTo.Visible = False
                rowBillTo.Visible = False
                Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(gridItem.DataKeys(Index).Values("Booking_no"))
                ' ViewState("Payin") = dsBooking.Tables(0).Rows(0).Item("Payin")
                ViewState("Payin") = gridItem.DataKeys(Index).Values("Payin")
                ViewState("PORT") = gridItem.DataKeys(Index).Values("PORT")
                ViewState("SoldTo") = gridItem.DataKeys(Index).Values("MAgent_no")
                ViewState("SoldTo_Name") = gridItem.DataKeys(Index).Values("MAgent_name")
                Dim CUstomer_no As String = ""
                Dim chkAgent As Boolean = True


                If (gridItem.DataKeys(Index).Values("PORT") & "" = "B") Then
                    ViewState("SoldTo") = gridItem.DataKeys(Index).Values("Owner_Product_no") & ""
                    ViewState("SoldTo_Name") = gridItem.DataKeys(Index).Values("Owner_Product_name") & ""
                    CUstomer_no = gridItem.DataKeys(Index).Values("Owner_Product_no") & ""
                    If (gridItem.DataKeys(Index).Values("Type_Pay") & "" <> "") Then
                        ViewState("Payin") = gridItem.DataKeys(Index).Values("Type_Pay_Product")
                    End If
                    If (ViewState("SoldTo") <> dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                        chkAgent = False
                    End If
                    GridMat.Columns(0).Visible = True
                Else
                    GridMat.Columns(0).Visible = True
                End If
                If (dsBooking.Tables(0).Rows(0).Item("Bill_to_no") & "" = "") Then
                    ViewState("BillTo") = ViewState("SoldTo")
                Else
                    If (ViewState("SoldTo") <> dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                        ViewState("BillTo") = ViewState("SoldTo")
                    Else
                        ViewState("BillTo") = dsBooking.Tables(0).Rows(0).Item("Bill_to_no") & ""
                    End If
                End If

                ViewState("Vehicle_Text") = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                If (gridItem.DataKeys(Index).Values("PORT") = "L") Then
                    ViewState("Plant") = "1103"
                Else
                    ViewState("Plant") = "1104"
                End If
                If (gridItem.DataKeys(Index).Values("Status") & "" = "FN") Then
                    btnComplete.Visible = False
                    btnSave.Visible = False
                    btnPrintCNDN.Visible = True
                    rowAddTariff.Visible = False
                Else
                    btnComplete.Visible = True
                    btnSave.Visible = True
                    btnPrintCNDN.Visible = False
                    rowAddTariff.Visible = True
                End If
                Dim dtMat As DataTable
                Dim Bulk As Boolean = True
                If (ViewState("PORT") & "" = "B") Then
                    dtMat = clsGet.GetActual_Data_Backup_For_Billing(ViewState("EditBooking"), ViewState("SoldTo"), False)
                    If (dtMat.Rows.Count = 0) And (gridItem.DataKeys(Index).Values("Status") & "" = "FN") Then
                        Bulk = False

                    End If
                Else
                    dtMat = clsGet.GetActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", False)
                End If

                Dim Ret As Integer = 1
                If (dtMat.Rows.Count = 0) And (Bulk) Then

                    'Check Shifting
                    Dim dtWharf As DataTable = clsGet.Get_BookingWharf(ViewState("EditBooking"))
                    Dim Shifting As Boolean = False
                    Dim BookingShifting As String = ""
                    If (dtWharf.Rows.Count > 0) Then
                        If (dtWharf.Rows(0).Item("Shift_Booking") & "" <> "") Then
                            Shifting = True
                            BookingShifting = dtWharf.Rows(0).Item("Shift_Booking")
                        End If
                    End If

                    dtMat = clsGet.GetBookingTariff_Actual(ViewState("EditBooking"), "", "")
                    If (dtMat.Rows.Count = 0) Then
                        'เข้ามาครั้งแรกต้องทำการ Insert ข้อมูล Mat
                        If Not (SaveTariffActual(ViewState("EditBooking"), Ret)) Then
                            'Insert ไม่สำเร็จ
                            PanelBookingItem.Visible = True
                            PanelOperation.Visible = False
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('พบความผิดพลาดในการดึงข้อมูล กรุณาลองใหม่อีกครั้ง !!');", True)
                            Exit Sub
                        End If
                    End If

                    dtMat = clsGet.GetTemp_Estimate(ViewState("EditBooking"), CUstomer_no)
                    Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
                    Dim dtLog_Out As DataTable
                    If (Shifting) Then
                        dtLog_Out = clsGet.Get_Booking_LogSheet_Out(BookingShifting)
                        If (dtLog_Out.Rows.Count = 0) Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูลของเรือ Shiting Booking No.: " & BookingShifting & " !!');", True)
                            Exit Sub
                        End If
                    Else
                        dtLog_Out = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
                    End If


                    Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
                    If (Berthing_Date.Trim().Length < 9) Then
                        Try
                            Dim days As String = Berthing_Date.Substring(0, 2)
                            Dim Month As String = GetNameMonth(Berthing_Date.Substring(3, 2))
                            Dim Year As String = "20" & Berthing_Date.Substring(6, 2)
                            Berthing_Date = days & " " & Month & " " & Year
                        Catch ex As Exception

                        End Try
                    End If
                    Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
                    If (Depart_Actual_Date.Trim().Length < 9) Then
                        Try
                            Dim days As String = Depart_Actual_Date.Substring(0, 2)
                            Dim Month As String = GetNameMonth(Depart_Actual_Date.Substring(3, 2))
                            Dim Year As String = "20" & Depart_Actual_Date.Substring(6, 2)
                            Depart_Actual_Date = days & " " & Month & " " & Year
                        Catch ex As Exception

                        End Try
                    End If

                    Dim ts = DateDiff("n", Berthing_Date & " " & dtActual.Rows(0).Item("Berthing_TimeFrom"), Depart_Actual_Date & " " & dtLog_Out.Rows(0).Item("Last_Time")) ' in case you need it in minutes

                    Dim StartDay As Integer = CDate(ClassFunctionGetData.CDateT(Berthing_Date)).ToString("dd")
                    Dim StartMonth As Integer = CDate(ClassFunctionGetData.CDateT(Berthing_Date)).ToString("MM")

                    Dim StartYear As Integer = CInt(Berthing_Date.Split(" ")(2))
                    Dim EndDay As Integer = CDate(ClassFunctionGetData.CDateT(Depart_Actual_Date)).ToString("dd")
                    Dim EndMonth As Integer = CDate(ClassFunctionGetData.CDateT(Depart_Actual_Date)).ToString("MM")
                    Dim EndYear As Integer = CInt(Depart_Actual_Date.Split(" ")(2))


                    ' Dim StandartTIme As Integer = (ts / 60)
                    Dim StandartTIme As Double = (ts / 60).ToString("###################.00")
                    Try
                        If (CInt(StandartTIme.ToString.Split(".")(1)) > 49) Then
                            StandartTIme = CDbl(StandartTIme.ToString.Split(".")(0)) + 1
                        ElseIf (CInt(StandartTIme.ToString.Split(".")(1)) > 0) Then
                            StandartTIme = CDbl(StandartTIme.ToString.Split(".")(0)) + 0.5
                        End If
                    Catch ex As Exception

                    End Try


                    Dim Day As Integer = 0
                    'If (StartYear = EndYear) Then
                    If (StartMonth = EndMonth) Then
                        Day = (EndDay - StartDay) + 1
                    Else
                        Day = ((Date.DaysInMonth(StartDay, StartMonth) - StartDay) + EndDay) + 1
                    End If
                    dtMat = SetStructure(dtMat)
                    CheckTugWaterElectric(dtMat)
                    CheckTruck(dtMat)


                    Dim GRT As String = 0.0
                    Dim DWT As String = 0.0
                    Dim LOA As String = 0.0
                    Dim Draft As String = 0.0
                    GetValueVessel(gridItem.DataKeys(Index).Values("Vehicle_no"), GRT, LOA, DWT, Draft)
                    Dim RememberRow As String = ""
                    For i As Integer = 0 To dtMat.Rows.Count - 1

                        Dim BL As Double = 0.0
                        If (gridItem.DataKeys(Index).Values("PORT") & "" = "L") Then
                            Dim dtProduct As DataTable = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), "")
                            If (dtProduct.Rows.Count > 0) Then
                                For Each dp As DataRow In dtProduct.Rows
                                    Try
                                        BL += CDbl(dp.Item("LU_BLMT"))
                                    Catch ex As Exception

                                    End Try
                                Next
                                dtMat.Rows(i).Item("data1") = BL
                            End If
                            If (Shifting) Then
                                dtProduct = clsGet.Get_Load_Unload_Product(BookingShifting, "")
                                If (dtProduct.Rows.Count > 0) Then
                                    For Each dp As DataRow In dtProduct.Rows
                                        Try
                                            BL += CDbl(dp.Item("LU_BLMT"))
                                        Catch ex As Exception

                                        End Try
                                    Next
                                    dtMat.Rows(i).Item("data1") = BL
                                End If
                            End If
                        Else
                            If (dtMat.Rows(i).Item("MATERIAL") & "" = "000000002100000268") Then
                                Dim dtProduct As DataTable = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), "")
                                Dim ProductTemp As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"), ViewState("SoldTo"))
                                If (dtProduct.Rows.Count > 0) Then
                                    If (chkAgent) Then
                                        BL = 0.0
                                        Try
                                            For Each drr As DataRow In dtProduct.Rows
                                                If (dtProduct.Rows(0).Item("BU_Bill") & "" = "") Then
                                                    BL += CDbl(dtProduct.Rows(0).Item("BU_Manifest"))
                                                Else
                                                    BL += CDbl(dtProduct.Rows(0).Item("BU_Bill"))
                                                    dtMat.Rows(i).Item("data1") = CDbl(BL)
                                                End If
                                            Next

                                            dtMat.Rows(i).Item("data1") = CDbl(BL)
                                        Catch ex As Exception

                                        End Try
                                    Else
                                        BL = 0.0
                                        Try
                                            For Each drpro As DataRow In ProductTemp.Rows
                                                For Each drr As DataRow In dtProduct.Rows
                                                    If (drpro.Item("BP_Code") = drr.Item("BP_Code")) Then
                                                        If (drr.Item("BU_Bill") & "" = "") Then
                                                            BL += CDbl(drr.Item("BU_Manifest"))
                                                        Else
                                                            BL += CDbl(drr.Item("BU_Bill"))
                                                            dtMat.Rows(i).Item("data1") = CDbl(BL)
                                                        End If
                                                    End If
                                                Next
                                            Next

                                            dtMat.Rows(i).Item("data1") = CDbl(BL)
                                        Catch ex As Exception

                                        End Try
                                    End If


                                End If
                                If (Shifting) Then
                                    dtProduct = clsGet.Get_Load_Unload_Product(BookingShifting, "")
                                    ProductTemp = clsGet.Get_Booking_Product(BookingShifting, ViewState("SoldTo"))
                                    If (dtProduct.Rows.Count > 0) Then
                                        If (chkAgent) Then
                                            Try
                                                For Each drr As DataRow In dtProduct.Rows
                                                    If (dtProduct.Rows(0).Item("BU_Bill") & "" = "") Then
                                                        BL += CDbl(dtProduct.Rows(0).Item("BU_Manifest"))
                                                    Else
                                                        BL += CDbl(dtProduct.Rows(0).Item("BU_Bill"))
                                                        dtMat.Rows(i).Item("data1") = CDbl(BL)
                                                    End If
                                                Next

                                                dtMat.Rows(i).Item("data1") = CDbl(BL)
                                            Catch ex As Exception

                                            End Try
                                        Else
                                            Try
                                                For Each drpro As DataRow In ProductTemp.Rows
                                                    For Each drr As DataRow In dtProduct.Rows
                                                        If (drpro.Item("BP_Code") = drr.Item("BP_Code")) Then
                                                            If (drr.Item("BU_Bill") & "" = "") Then
                                                                BL += CDbl(drr.Item("BU_Manifest"))
                                                            Else
                                                                BL += CDbl(drr.Item("BU_Bill"))
                                                                dtMat.Rows(i).Item("data1") = CDbl(BL)
                                                            End If
                                                        End If
                                                    Next
                                                Next

                                                dtMat.Rows(i).Item("data1") = CDbl(BL)
                                            Catch ex As Exception

                                            End Try
                                        End If



                                    End If
                                End If
                            Else
                                Dim dtProduct As DataTable = clsGet.Get_Load_Unload_Product_Bulk(ViewState("EditBooking"), "", "")
                                Dim ProductTemp As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"), ViewState("SoldTo"))
                                If (dtProduct.Rows.Count > 0) Then
                                    If (chkAgent) Then
                                        For Each dp As DataRow In dtProduct.Rows
                                            Try
                                                BL += CDbl(dp.Item("_M"))
                                            Catch ex As Exception

                                            End Try
                                        Next
                                    Else
                                        For Each dp As DataRow In dtProduct.Rows
                                            For Each dpro As DataRow In ProductTemp.Rows
                                                If (dp.Item("BP_CODE") = dpro.Item("BP_CODE")) Then
                                                    Try
                                                        BL += CDbl(dp.Item("_M"))
                                                    Catch ex As Exception

                                                    End Try
                                                End If
                                            Next
                                        Next
                                    End If

                                    dtMat.Rows(i).Item("data1") = BL
                                End If
                                If (Shifting) Then
                                    dtProduct = clsGet.Get_Load_Unload_Product_Bulk(BookingShifting, "", "")
                                    ProductTemp = clsGet.Get_Booking_Product(BookingShifting, ViewState("SoldTo"))
                                    If (dtProduct.Rows.Count > 0) Then
                                        If (chkAgent) Then
                                            For Each dp As DataRow In dtProduct.Rows
                                                Try
                                                    BL += CDbl(dp.Item("_M"))
                                                Catch ex As Exception

                                                End Try
                                            Next
                                        Else
                                            For Each dp As DataRow In dtProduct.Rows
                                                For Each dpro As DataRow In ProductTemp.Rows
                                                    If (dp.Item("BP_CODE") = dpro.Item("BP_CODE")) Then
                                                        Try
                                                            BL += CDbl(dp.Item("_M"))
                                                        Catch ex As Exception

                                                        End Try
                                                    End If
                                                Next
                                            Next
                                        End If

                                        dtMat.Rows(i).Item("data1") = BL
                                    End If
                                End If
                            End If


                        End If
                        'Check Shifting
                        If (Shifting) Then
                            Dim dtMaterial As DataTable = clsGet.Get_MeterailAllField(dtMat.Rows(i).Item("Material") & "")
                            Try
                                If (dtMaterial.Rows(0).Item("MAT_Shifting") & "" <> "") Or (dtMaterial.Rows(0).Item("MAT_Shifting") & "" <> "0") Then
                                    Dim Plus As Double = CDbl(dtMaterial.Rows(0).Item("MAT_Shifting"))
                                    dtMat.Rows(i).Item("data3") = CDbl(dtMat.Rows(i).Item("data3")) + Plus
                                End If
                            Catch ex As Exception

                            End Try

                        End If

                        dtMat.AcceptChanges()
                        Dim CNTRY As String = gridItem.DataKeys(Index).Values("Vehicle_CNTRY")
                        If (CNTRY = "TH") Or (CNTRY = "T") Then
                            CNTRY = "T"
                        Else
                            CNTRY = "O"
                        End If
                        Dim dtNewValue As DataTable = ComputeMoney(dtMat.Rows(i).Item("MATERIAL"), GRT, LOA, DWT, Draft, BL, ViewState("SoldTo"), gridItem.DataKeys(Index).Values("PORT") & "", StandartTIme, Day, dtMat.Rows(i).Item("data3"), gridItem.DataKeys(Index).Values("Vehicle_Destination"), CNTRY)
                        If (dtNewValue.Rows.Count > 0) Then
                            dtMat.Rows(i).Item("data1") = dtNewValue.Rows(0).Item("data1")
                            dtMat.Rows(i).Item("data2") = dtNewValue.Rows(0).Item("data2")
                            dtMat.Rows(i).Item("data3") = dtNewValue.Rows(0).Item("data3")
                            dtMat.Rows(i).Item("data4") = dtNewValue.Rows(0).Item("data4")
                            dtMat.AcceptChanges()
                        Else
                            RememberRow &= i.ToString() & "$"
                        End If
                    Next
                    If (RememberRow <> "") Then
                        Dim row() As String = RememberRow.Split("$")
                        For x As Integer = 0 To row.Length - 1
                            If (row((row.Length - 1) - x) <> "") Then
                                Try
                                    Dim rowindex As Integer = CInt(row((row.Length - 1) - x))
                                    dtMat.Rows(rowindex).Delete()
                                    dtMat.AcceptChanges()
                                Catch ex As Exception

                                End Try
                            End If
                        Next
                    End If
                End If
                ' ViewState("dtMat") = dtMat
                Dim c As Integer = 0
                Dim dtT As DataTable = dtMat.Copy
                For i As Integer = 0 To dtMat.Rows.Count - 1
                    If (dtMat.Rows(i).Item("data4") & "" = "0.00") Then
                        dtT.Rows(i - c).Delete()
                        dtT.AcceptChanges()
                        c += 1
                    End If
                Next
                dtMat = dtT


                ViewState("dtMat") = dtMat
                If (Ret = 0) Then
                    InsertBookingTariff_Actual_Same_Actual_Data_Backup_For_Billing()
                End If
                If (dtMat.Rows.Count > 0) Then
                    If (gridItem.DataKeys(Index).Values("MAgent_no") & "" = "") Then
                        rowSoldTo.Visible = True
                        rowBillTo.Visible = True
                    End If
                End If

                GridMat.DataSource = dtMat
                GridMat.DataBind()

                If Not ((ViewState("EditBooking").ToString.Substring(0, 1) = "B") Or (ViewState("EditBooking").ToString.Substring(0, 1) = "S")) Then
                    For i As Integer = 0 To GridMat.Rows.Count - 1
                        Dim chk As CheckBox = CType(GridMat.Rows(i).FindControl("chk"), CheckBox)
                        chk.Checked = True
                    Next
                End If

                gridTariff.DataSource = dtMat
                gridTariff.DataBind()

                'If Not (ChkBarge) Then
                '    If (ViewState("PORT") & "" = "B") Then
                '        Dim Owner() As String = ViewState("OwnerColumn").ToString.Split("$")
                '        For i As Integer = 0 To Owner.Length - 1
                '            Dim Ownerid As String = ""
                '            If Not (Owner(i).ToString.Split("฿")(0) & "" = "MAgent_no") Then
                '                Ownerid = Owner(i).ToString.Split("฿")(0) & ""
                '            End If
                '            Dim dt As DataTable = clsGet.Get_Owner(ViewState("EditBooking"), Ownerid, "")
                '            If (dt.Rows.Count > 0) Then
                '                'For Each dr As DataRow In dt.Rows
                '                '    For f As Integer = 0 To GridMat.Rows.Count - 1
                '                '        If (GridMat.DataKeys(f).Values("MATERIAL") & "" = dr.Item("MATERIAL") & "") Then
                '                '            Dim chk As CheckBox = CType(GridMat.Rows(f).FindControl("chkOwner" & (i + 1)), CheckBox)
                '                '            chk.Checked = True
                '                '            Exit For
                '                '        End If
                '                '    Next
                '                'Next
                '                For f As Integer = 0 To GridMat.Rows.Count - 1
                '                    Dim chkxx As Boolean = True
                '                    Dim chk As CheckBox = CType(GridMat.Rows(f).FindControl("chkOwner" & (i + 1)), CheckBox)
                '                    For Each dr As DataRow In dt.Rows
                '                        If (GridMat.DataKeys(f).Values("MATERIAL") & "" = dr.Item("MATERIAL") & "") Then
                '                            chk.Checked = True
                '                            chkxx = False
                '                            Exit For
                '                        End If
                '                    Next
                '                    If (chkxx) Then
                '                        chk.Checked = False
                '                    End If
                '                Next
                '            End If
                '        Next
                '    End If
                'End If

            End If
            SHowData()
            If (ChkBarge) Then
                lbAgent.Text = gridItem.Rows(Index).Cells(11).Text
            End If
            PanelBookingItem.Visible = False
            PanelOperation.Visible = True


        End If
    End Sub

    Private Sub SHowData()
        lbBooking_no.Text = ViewState("EditBooking")
        lbAgent.Text = ViewState("SoldTo") & " - " & ViewState("SoldTo_Name")
        If (ViewState("Payin") & "" = "0") Then
            lbType_Pay.Text = "CASH SALE"
        Else
            lbType_Pay.Text = "CREDIT SALE"
        End If
        Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
        Dim dtLog_Out As DataTable = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))

        Dim Berthing_Date As String = ""
        Try
            Berthing_Date = dtActual.Rows(0).Item("Berthing_Date")
            If (Berthing_Date.Trim().Length < 9) Then

                Dim days As String = Berthing_Date.Substring(0, 2)
                Dim Month As String = GetNameMonth(Berthing_Date.Substring(3, 2))
                Dim Year As String = "20" & Berthing_Date.Substring(6, 2)
                Berthing_Date = days & " " & Month & " " & Year
            End If
        Catch ex As Exception

        End Try

        Dim Depart_Actual_Date As String = ""
        Try
            Depart_Actual_Date = dtLog_Out.Rows(0).Item("Last_Date")
            If (Depart_Actual_Date.Trim().Length < 9) Then

                Dim days As String = Depart_Actual_Date.Substring(0, 2)
                Dim Month As String = GetNameMonth(Depart_Actual_Date.Substring(3, 2))
                Dim Year As String = "20" & Depart_Actual_Date.Substring(6, 2)
                Depart_Actual_Date = days & " " & Month & " " & Year
            End If
        Catch ex As Exception

        End Try

        Try
            If (ViewState("EditBooking").ToString.Substring(0, 1) <> "B") Then
                lbBerth.Text = Berthing_Date & " " & dtActual.Rows(0).Item("Berthing_TimeFrom") & " - " & Depart_Actual_Date & " " & dtLog_Out.Rows(0).Item("Last_Time")
            End If
        Catch ex As Exception
            lbBerth.Text = ""
        End Try
        Dim str As String = clsGet.Get_Wharf_Shifting(ViewState("EditBooking"))
        If (str <> "") Then
            Try
                rowShifting.Visible = True
            Catch ex As Exception
                rowShifting.Visible = False
            End Try
        Else
            rowShifting.Visible = False
        End If
    End Sub

    Private Sub CheckTugWaterElectric(ByRef dtMat As DataTable)
        Dim dtTug As DataTable = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "", "W")
        'Working
        Dim Tug As Integer = 0
        Dim Boat As Integer = 0
        Dim Hour_EXCEED As Integer = 0
        Dim Hour_EXCEED_Boat As Integer = 0
        For Each dr As DataRow In dtTug.Rows
            If (dr.Item("Tug_Name") & "" <> "") Then
                Dim Hrs As String = dr.Item("Hrs")
                Dim hours As Integer = CInt(Hrs.Split(":")(0))
                If (hours > 3) Then
                    Hour_EXCEED += hours - 4
                    If (CInt(Hrs.Split(":")(1)) > 0) Then
                        Hour_EXCEED += 1
                    End If
                End If
                Dim dttugType As DataTable = clsGet.Get_TugBoat(dr.Item("Tug_Name"))
                If (dttugType.Rows.Count > 0) Then
                    If (dttugType.Rows(0).Item("Tug_Type") & "" = "0") Then
                        Tug += 1
                    Else
                        If (dr.Item("Tug_Event") & "" = "W") Then
                            Boat += 1
                        Else
                            Tug += 1
                        End If

                    End If
                End If


            End If
        Next

        'Shifting *****************************
        Dim dtWharf As DataTable = clsGet.Get_BookingWharf(ViewState("EditBooking"))
        Dim Shifting As Boolean = False
        Dim BookingShifting As String = ""
        If (dtWharf.Rows.Count > 0) Then
            If (dtWharf.Rows(0).Item("Shift_Booking") & "" <> "") Then
                Shifting = True
                BookingShifting = dtWharf.Rows(0).Item("Shift_Booking")
            End If
        End If
        If (Shifting) Then

            dtTug = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "I", "W")
            'Working
            Tug = 0
            Boat = 0
            Hour_EXCEED = 0
            Hour_EXCEED_Boat = 0
            For Each dr As DataRow In dtTug.Rows
                If (dr.Item("Tug_Name") & "" <> "") Then
                    Dim Hrs As String = dr.Item("Hrs")
                    Dim hours As Integer = CInt(Hrs.Split(":")(0))
                    If (hours > 3) Then
                        Hour_EXCEED += hours - 4
                        If (CInt(Hrs.Split(":")(1)) > 0) Then
                            Hour_EXCEED += 1
                        End If
                    End If
                    Dim dttugType As DataTable = clsGet.Get_TugBoat(dr.Item("Tug_Name"))
                    If (dttugType.Rows.Count > 0) Then
                        If (dttugType.Rows(0).Item("Tug_Type") & "" = "0") Then
                            Tug += 1
                        Else
                            If (dr.Item("Tug_Event") & "" = "W") Then
                                Boat += 1
                            Else
                                Tug += 1
                            End If

                        End If
                    End If


                End If
            Next
            dtTug = clsGet.Get_Booking_LogSheet_Tug(BookingShifting, "O", "W")
            'Working
            For Each dr As DataRow In dtTug.Rows
                If (dr.Item("Tug_Name") & "" <> "") Then
                    Dim Hrs As String = dr.Item("Hrs")
                    Dim hours As Integer = CInt(Hrs.Split(":")(0))
                    If (hours > 3) Then
                        Hour_EXCEED += hours - 4
                        If (CInt(Hrs.Split(":")(1)) > 0) Then
                            Hour_EXCEED += 1
                        End If
                    End If
                    Dim dttugType As DataTable = clsGet.Get_TugBoat(dr.Item("Tug_Name"))
                    If (dttugType.Rows.Count > 0) Then
                        If (dttugType.Rows(0).Item("Tug_Type") & "" = "0") Then
                            Tug += 1
                        Else
                            If (dr.Item("Tug_Event") & "" = "W") Then
                                Boat += 1
                            Else
                                Tug += 1
                            End If

                        End If
                    End If


                End If
            Next
            Dim HourShifting As Integer = 0
            Dim MinuteHour As Integer = 0
            Dim dtTemptug As DataTable
            dtTug = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "O", "W")
            For Each dr As DataRow In dtTug.Rows
                If (dr.Item("Hrs") & "" <> "") Then
                    dtTemptug = clsGet.Get_Booking_LogSheet_Tug(BookingShifting, "I", "W")
                    For Each dts As DataRow In dtTemptug.Rows
                        If (dts.Item("Tug_Code") = dr.Item("Tug_Code")) Then
                            MinuteHour = (CInt(dr.Item("Hrs").ToString.Split(":")(0)) * 60) + (CInt(dts.Item("Hrs").ToString.Split(":")(0)) * 60) + (CInt(dr.Item("Hrs").ToString.Split(":")(1))) + (CInt(dts.Item("Hrs").ToString.Split(":")(1)))
                            HourShifting += CInt(MinuteHour \ 60)
                            If (MinuteHour Mod 60) > 0 Then
                                HourShifting += 1
                            End If
                        End If
                    Next
                End If
            Next


            Dim CShifting As Boolean = True
            For Each dr As DataRow In dtMat.Rows
                If (dr.Item("MATERIAL") = "000000002100000240") Then
                    CShifting = False
                    If (HourShifting > 0) Then
                        dr.Item("data3") = HourShifting
                        dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * HourShifting).ToString()
                    Else
                        dr.Delete()
                    End If
                    dtMat.AcceptChanges()
                    Exit For
                End If
            Next
            If (HourShifting > 0) Then
                If (CShifting) Then
                    Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000240", ViewState("Plant"))
                    If (dtOne.Tables(0).Rows.Count > 0) Then
                        Dim dr As DataRow = dtMat.NewRow()

                        dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                        dr.Item("Booking_no") = ViewState("EditBooking")
                        dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                        dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                        dr.Item("Count") = HourShifting
                        dr.Item("MAT_Default") = "N"
                        dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                        dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                        dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                        dr.Item("MAT_Compute") = "Y"
                        dr.Item("MAT_Free") = "N"
                        dr.Item("data1") = ""
                        dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                        dr.Item("data3") = HourShifting
                        dr.Item("data4") = CDbl(Boat * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                        dr.Item("New_Old") = "N"
                        dr.Item("Owner") = ""
                        dtMat.Rows.Add(dr)
                        dtMat.AcceptChanges()
                    End If

                End If
            End If
        End If

        Dim CTug As Boolean = True
        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000236") Then
                CTug = False
                If (Tug > 0) Then
                    dr.Item("data3") = Tug
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Tug).ToString()
                Else
                    dr.Delete()
                End If
                dtMat.AcceptChanges()
                Exit For
            End If
        Next
        If (Tug > 0) Then
            If (CTug) Then
                Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000236", ViewState("Plant"))
                If (dtOne.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dtMat.NewRow()

                    dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Tug
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Tug
                    dr.Item("data4") = CDbl(Tug * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dtMat.Rows.Add(dr)
                    dtMat.AcceptChanges()
                End If

            End If
        End If

        CTug = True
        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000237") Then
                CTug = False
                If (Boat > 0) Then
                    dr.Item("data3") = Boat
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Boat).ToString()
                Else
                    dr.Delete()
                End If
                dtMat.AcceptChanges()
                Exit For
            End If
        Next
        If (Boat > 0) Then
            If (CTug) Then
                Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000237", ViewState("Plant"))
                If (dtOne.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dtMat.NewRow()

                    dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Boat
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Boat
                    dr.Item("data4") = CDbl(Boat * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dtMat.Rows.Add(dr)
                    dtMat.AcceptChanges()
                End If

            End If
        End If

        CTug = True
        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000232") Then
                CTug = False
                If (Hour_EXCEED > 0) Then
                    dr.Item("data3") = Hour_EXCEED
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Hour_EXCEED).ToString()
                Else
                    dr.Delete()
                End If
                dtMat.AcceptChanges()
                Exit For
            End If
        Next
        If (Hour_EXCEED > 0) Then
            If (CTug) Then
                Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000232", ViewState("Plant"))
                If (dtOne.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dtMat.NewRow()

                    dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Hour_EXCEED
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Hour_EXCEED
                    dr.Item("data4") = CDbl(Hour_EXCEED * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dtMat.Rows.Add(dr)
                    dtMat.AcceptChanges()
                End If

            End If
        End If
        CTug = True
        Dim Hour As Integer = 0
        Dim Minute As Integer = 0
        If (Shifting) Then
            dtTug = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "I", "P")
            'PILOT TRANSPORTATION

            For Each dr As DataRow In dtTug.Rows
                Minute = 0
                If (dr.Item("Tug_Name") & "" <> "") Then
                    PlusHour(Hour, Minute, CInt(dr.Item("Hrs").ToString().Split(":")(0)), CInt(dr.Item("Hrs").ToString().Split(":")(1)))
                End If
                If (Minute > 0) Then
                    Hour += 1
                End If
            Next
            dtTug = clsGet.Get_Booking_LogSheet_Tug(BookingShifting, "O", "P")
            'PILOT TRANSPORTATION

            For Each dr As DataRow In dtTug.Rows
                Minute = 0
                If (dr.Item("Tug_Name") & "" <> "") Then
                    PlusHour(Hour, Minute, CInt(dr.Item("Hrs").ToString().Split(":")(0)), CInt(dr.Item("Hrs").ToString().Split(":")(1)))
                End If
                If (Minute > 0) Then
                    Hour += 1
                End If
            Next
        Else
            dtTug = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "", "P")
            'PILOT TRANSPORTATION
            For Each dr As DataRow In dtTug.Rows
                Minute = 0
                If (dr.Item("Tug_Name") & "" <> "") Then
                    PlusHour(Hour, Minute, CInt(dr.Item("Hrs").ToString().Split(":")(0)), CInt(dr.Item("Hrs").ToString().Split(":")(1)))
                End If
                If (Minute > 0) Then
                    Hour += 1
                End If
            Next
        End If


        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000238") Then
                CTug = False
                If (Tug > 0) Then
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Hour).ToString()
                Else
                    dr.Delete()
                End If
                dtMat.AcceptChanges()
                Exit For
            End If
        Next
        If (CTug) Then
            If Hour > 0 Then
                Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000238", ViewState("Plant"))
                If (dtOne.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dtMat.NewRow()

                    dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Hour
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(Hour * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dtMat.Rows.Add(dr)
                    dtMat.AcceptChanges()
                End If
            End If


        End If

        dtTug = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "", "S")
        'Stand By
        CTug = True
        Hour = 0
        Minute = 0
        For Each dr As DataRow In dtTug.Rows
            If (dr.Item("Tug_Name") & "" <> "") Then
                PlusHour(Hour, Minute, CInt(dr.Item("Hrs").ToString().Split(":")(0)), CInt(dr.Item("Hrs").ToString().Split(":")(1)))
            End If
        Next
        If (Minute > 0) Then
            Hour += 1
        End If
        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000242") Then
                CTug = False
                If (Hour > 0) Then
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Hour).ToString()
                Else
                    dr.Delete()
                End If
                dtMat.AcceptChanges()
                Exit For
            End If
        Next
        If (Hour > 0) Then
            If (CTug) Then
                Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000242", ViewState("Plant"))
                If (dtOne.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dtMat.NewRow()

                    dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Hour
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(Hour * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dtMat.Rows.Add(dr)
                    dtMat.AcceptChanges()
                End If

            End If
        End If


        dtTug = clsGet.Get_Booking_LogSheet_Tug(ViewState("EditBooking"), "", "O")
        'Other
        CTug = True
        Hour = 0
        Minute = 0
        For Each dr As DataRow In dtTug.Rows
            If (dr.Item("Tug_Name") & "" <> "") Then
                PlusHour(Hour, Minute, CInt(dr.Item("Hrs").ToString().Split(":")(0)), CInt(dr.Item("Hrs").ToString().Split(":")(1)))
            End If
        Next
        If (Minute > 0) Then
            Hour += 1
        End If
        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000234") Then
                CTug = False
                If (Hour > 0) Then
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Hour).ToString()
                Else
                    dr.Delete()
                End If
                dtMat.AcceptChanges()
                Exit For
            End If
        Next
        If (Hour > 0) Then
            If (CTug) Then
                Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000234", ViewState("Plant"))
                If (dtOne.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dtMat.NewRow()

                    dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Hour
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(Hour * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dtMat.Rows.Add(dr)
                    dtMat.AcceptChanges()
                End If

            End If
        End If
        '****************************************
        'Mooring
        '****************************************
        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000184") Then
                dr.Item("data3") = "1"
                dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Hour).ToString()
                dtMat.AcceptChanges()
                Exit For
            End If
        Next


        '**************************************************
        'Pilot
        '************************************************
        dtTug = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
        CTug = True
        Hour = 0
        If (dtTug.Rows.Count > 0) Then
            If (dtTug.Rows(0).Item("Pilot").ToString.Trim() & "" <> "") Then
                Hour = 1
            End If
        End If
        dtTug = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))

        If (dtTug.Rows.Count > 0) Then
            If (dtTug.Rows(0).Item("Pilot").ToString.Trim() & "" <> "") Then
                If (Hour = 0) Then
                    Hour = 1
                End If
            End If
        End If

        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("MATERIAL") = "000000002100000197") Then
                CTug = False
                If (Hour > 0) Then
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Hour).ToString()
                Else
                    dr.Delete()
                End If
                dtMat.AcceptChanges()
                Exit For
            End If
        Next
        If (Hour > 0) Then
            If (CTug) Then
                Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000197", ViewState("Plant"))
                If (dtOne.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dtMat.NewRow()

                    dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Hour
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Hour
                    dr.Item("data4") = CDbl(Hour * CDbl(dtOne.Tables(0).Rows(0).Item("KBETR"))).ToString("#############0.00")
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dtMat.Rows.Add(dr)
                    dtMat.AcceptChanges()
                End If

            End If
        End If

        '************************************************
        'Water
        '************************************************
        dtTug = clsGet.Get_Load_Unload_Addition(ViewState("EditBooking"))
        If (dtTug.Rows.Count > 0) Then
            If (CDbl(dtTug.Rows(0).Item("Water")) > 0) Then
                CTug = True
                Dim dtRelation As DataTable = clsGet.Get_MeterailRelation("WP")
                Dim LowRate As String = ""
                Dim MAT_Rate As String = ""
                If (dtRelation.Rows.Count > 0) Then
                    LowRate = dtRelation.Rows(0).Item("LowRate") & ""
                    MAT_Rate = dtRelation.Rows(0).Item("MAT_Rate") & ""
                End If
                For Each dr As DataRow In dtMat.Rows
                    If (dr.Item("MATERIAL") = "WP") Then
                        CTug = False
                        If (CDbl(dtTug.Rows(0).Item("Water")) > 0) Then
                            If LowRate = "" Then
                                dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Water"))).ToString("#############0.00")
                            Else
                                If (CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Water"))) <= CDbl(LowRate)) Then
                                    dr.Item("data2") = CDbl(LowRate).ToString("###########0.00")
                                    dr.Item("data4") = CDbl(LowRate).ToString("###########0.00")
                                Else
                                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Water"))).ToString("#############0.00")
                                End If
                            End If

                            dr.Item("data3") = dtTug.Rows(0).Item("Water") & ""
                        Else
                            dr.Delete()
                        End If
                        dtMat.AcceptChanges()
                        Exit For
                    End If
                Next
                If (CTug) Then
                    Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("WP", ViewState("Plant"))

                    If (dtOne.Tables(0).Rows.Count > 0) Then
                        Dim dr As DataRow = dtMat.NewRow()

                        dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                        dr.Item("Booking_no") = ViewState("EditBooking")
                        dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                        dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                        dr.Item("Count") = dtTug.Rows(0).Item("Water")
                        dr.Item("MAT_Default") = "N"

                        dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                        dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                        dr.Item("MAT_Compute") = "Y"
                        dr.Item("MAT_Free") = "N"
                        dr.Item("data1") = ""
                        If (MAT_Rate <> "") Then
                            dr.Item("data2") = dtRelation.Rows(0).Item("MAT_Rate")
                            dr.Item("KBETR") = dtRelation.Rows(0).Item("MAT_Rate")
                        Else
                            dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR")
                            dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                        End If

                        dr.Item("data3") = dtTug.Rows(0).Item("Water")
                        If (LowRate = "") Then
                            dr.Item("data4") = CDbl(CDbl(dtTug.Rows(0).Item("Water")) * CDbl(dr.Item("data2"))).ToString("################0.00")
                        ElseIf (CDbl(LowRate) > CDbl(CDbl(dtTug.Rows(0).Item("Water")) * CDbl(dr.Item("data2")))) Then
                            dr.Item("data2") = CDbl(LowRate).ToString("###################0.00")
                            dr.Item("data4") = CDbl(LowRate).ToString("###################0.00")
                        Else
                            dr.Item("data4") = (CDbl(dr.Item("data2")) * CDbl(dr.Item("data3"))).ToString("#################0.00")
                        End If

                        dr.Item("New_Old") = "N"
                        dr.Item("Owner") = ""
                        dtMat.Rows.Add(dr)
                        dtMat.AcceptChanges()
                    End If

                End If
            End If

        End If
        '**************************************************
        'Electric
        '************************************************
        If (ViewState("PORT") & "" = "B") Then
            If (dtTug.Rows.Count > 0) Then
                If (CDbl(dtTug.Rows(0).Item("Electric")) > 0) Then
                    CTug = True
                    Dim dtRelation As DataTable = clsGet.Get_MeterailRelation("ELEC.POWER")
                    Dim LowRate As String = ""
                    Dim MAT_Rate As String = ""
                    If (dtRelation.Rows.Count > 0) Then
                        LowRate = dtRelation.Rows(0).Item("LowRate") & ""
                        MAT_Rate = dtRelation.Rows(0).Item("MAT_Rate") & ""
                    End If
                    For Each dr As DataRow In dtMat.Rows
                        If (dr.Item("MATERIAL") = "ELEC.POWER") Then
                            CTug = False
                            If (Tug > 0) Then
                                If LowRate = "" Then
                                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Electric"))).ToString("#############0.00")
                                Else
                                    If (CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Electric"))) <= CDbl(LowRate)) Then
                                        dr.Item("data2") = CDbl(LowRate).ToString("###########0.00")
                                        dr.Item("data4") = CDbl(LowRate).ToString("###########0.00")
                                    Else
                                        dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Electric"))).ToString("#############0.00")
                                    End If
                                End If

                                dr.Item("data3") = dtTug.Rows(0).Item("Electric") & ""
                            Else
                                dr.Delete()
                            End If
                            dtMat.AcceptChanges()
                            Exit For
                        End If
                    Next
                    If (CTug) Then
                        Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("ELEC.POWER", ViewState("Plant"))
                        If (dtOne.Tables(0).Rows.Count > 0) Then
                            Dim dr As DataRow = dtMat.NewRow()

                            dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                            dr.Item("Booking_no") = ViewState("EditBooking")
                            dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                            dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                            dr.Item("Count") = dtTug.Rows(0).Item("Electric")
                            dr.Item("MAT_Default") = "N"

                            dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                            dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                            dr.Item("MAT_Compute") = "Y"
                            dr.Item("MAT_Free") = "N"
                            dr.Item("data1") = ""
                            If (MAT_Rate <> "") Then
                                dr.Item("data2") = dtRelation.Rows(0).Item("MAT_Rate")
                                dr.Item("KBETR") = dtRelation.Rows(0).Item("MAT_Rate")
                            Else
                                dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR")
                                dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                            End If

                            dr.Item("data3") = dtTug.Rows(0).Item("Electric")
                            If (LowRate = "") Then
                                dr.Item("data4") = CDbl(CDbl(dtTug.Rows(0).Item("Electric")) * CDbl(dr.Item("data2"))).ToString("################0.00")
                            ElseIf (CDbl(LowRate) > CDbl(CDbl(dtTug.Rows(0).Item("Electric")) * CDbl(dr.Item("data2")))) Then
                                dr.Item("data2") = CDbl(LowRate).ToString("###################0.00")
                                dr.Item("data4") = CDbl(LowRate).ToString("###################0.00")
                            End If

                            dr.Item("New_Old") = "N"
                            dr.Item("Owner") = ""
                            dtMat.Rows.Add(dr)
                            dtMat.AcceptChanges()
                        End If

                    End If
                End If
                '*********************************
                'HOPPER
                '********************************
                If (CDbl(dtTug.Rows(0).Item("Hopper")) > 0) Then
                    CTug = True
                    Dim dtRelation As DataTable = clsGet.Get_MeterailRelation("000000002100000104")
                    Dim LowRate As String = ""
                    Dim MAT_Rate As String = ""
                    Dim CountHopper As Integer = 0
                    'คำนวณจำนวน Hopper


                    If (dtRelation.Rows.Count > 0) Then
                        LowRate = dtRelation.Rows(0).Item("LowRate") & ""
                        MAT_Rate = dtRelation.Rows(0).Item("MAT_Rate") & ""
                    End If
                    For Each dr As DataRow In dtMat.Rows
                        If (dr.Item("MATERIAL") = "000000002100000104") Then
                            CTug = False
                            If (CDbl(dtTug.Rows(0).Item("Hopper")) > 0) Then
                                If LowRate = "" Then
                                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(CountHopper)).ToString("#############0.00")
                                Else
                                    If (CDbl(CDbl(dr.Item("data2")) * CDbl(CountHopper)) <= CDbl(LowRate)) Then
                                        dr.Item("data2") = CDbl(LowRate).ToString("###########0.00")
                                        dr.Item("data4") = CDbl(LowRate).ToString("###########0.00")
                                    Else
                                        dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(CountHopper)).ToString("#############0.00")
                                    End If
                                End If

                                dr.Item("data3") = CountHopper
                            Else
                                dr.Delete()
                            End If
                            dtMat.AcceptChanges()
                            Exit For
                        End If
                    Next
                    If (CTug) Then
                        Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000104", ViewState("Plant"))

                        If (dtOne.Tables(0).Rows.Count > 0) Then
                            Dim dr As DataRow = dtMat.NewRow()

                            dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                            dr.Item("Booking_no") = ViewState("EditBooking")
                            dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                            dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                            dr.Item("Count") = CountHopper
                            dr.Item("MAT_Default") = "N"

                            dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                            dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                            dr.Item("MAT_Compute") = "Y"
                            dr.Item("MAT_Free") = "N"
                            dr.Item("data1") = ""
                            If (MAT_Rate <> "") Then
                                dr.Item("data2") = dtRelation.Rows(0).Item("MAT_Rate")
                                dr.Item("KBETR") = dtRelation.Rows(0).Item("MAT_Rate")
                            Else
                                dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR")
                                dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                            End If

                            dr.Item("data3") = CountHopper
                            If (LowRate = "") Then
                                dr.Item("data4") = CDbl(CDbl(CountHopper) * CDbl(dr.Item("data2"))).ToString("################0.00")
                            ElseIf (CDbl(LowRate) > CDbl(CDbl(CountHopper) * CDbl(dr.Item("data2")))) Then
                                dr.Item("data2") = CDbl(LowRate).ToString("###################0.00")
                                dr.Item("data4") = CDbl(LowRate).ToString("###################0.00")
                            Else
                                dr.Item("data4") = (CDbl(dr.Item("data2")) * CDbl(dr.Item("data3"))).ToString("#################0.00")
                            End If

                            dr.Item("New_Old") = "N"
                            dr.Item("Owner") = ""
                            dtMat.Rows.Add(dr)
                            dtMat.AcceptChanges()
                        End If

                    End If
                End If
            End If

        End If
        '*********************************
        'Nitrogen
        '********************************
        If (ViewState("PORT") & "" = "L") Then
            If (dtTug.Rows.Count > 0) Then
                If (CDbl(dtTug.Rows(0).Item("Nitrogen")) > 0) Then
                    CTug = True
                    Dim dtRelation As DataTable = clsGet.Get_MeterailRelation("000000002100000187")
                    Dim LowRate As String = ""
                    Dim MAT_Rate As String = ""
                    If (dtRelation.Rows.Count > 0) Then
                        LowRate = dtRelation.Rows(0).Item("LowRate") & ""
                        MAT_Rate = dtRelation.Rows(0).Item("MAT_Rate") & ""
                    End If
                    For Each dr As DataRow In dtMat.Rows
                        If (dr.Item("MATERIAL") = "000000002100000187") Then
                            CTug = False
                            If (CDbl(dtTug.Rows(0).Item("Nitrogen")) > 0) Then
                                If LowRate = "" Then
                                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Nitrogen"))).ToString("#############0.00")
                                Else
                                    If (CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Nitrogen"))) <= CDbl(LowRate)) Then
                                        dr.Item("data2") = CDbl(LowRate).ToString("###########0.00")
                                        dr.Item("data4") = CDbl(LowRate).ToString("###########0.00")
                                    Else
                                        dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * CDbl(dtTug.Rows(0).Item("Nitrogen"))).ToString("#############0.00")
                                    End If
                                End If

                                dr.Item("data3") = dtTug.Rows(0).Item("Nitrogen") & ""
                            Else
                                dr.Delete()
                            End If
                            dtMat.AcceptChanges()
                            Exit For
                        End If
                    Next
                    If (CTug) Then
                        Dim dtOne As DataSet = clsGet.Get_MeterailDefaultActual("000000002100000187", ViewState("Plant"))

                        If (dtOne.Tables(0).Rows.Count > 0) Then
                            Dim dr As DataRow = dtMat.NewRow()

                            dr.Item("MATERIAL") = dtOne.Tables(0).Rows(0).Item("MATERIAL")
                            dr.Item("Booking_no") = ViewState("EditBooking")
                            dr.Item("Text_line") = dtOne.Tables(0).Rows(0).Item("Text_line")
                            dr.Item("Unit") = dtOne.Tables(0).Rows(0).Item("Unit") & ""
                            dr.Item("Count") = dtTug.Rows(0).Item("Nitrogen")
                            dr.Item("MAT_Default") = "N"

                            dr.Item("KONWA") = dtOne.Tables(0).Rows(0).Item("KONWA") & ""
                            dr.Item("MAT_Relation") = dtOne.Tables(0).Rows(0).Item("Mat_Relation") & ""
                            dr.Item("MAT_Compute") = "Y"
                            dr.Item("MAT_Free") = "N"
                            dr.Item("data1") = ""
                            If (MAT_Rate <> "") Then
                                dr.Item("data2") = dtRelation.Rows(0).Item("MAT_Rate")
                                dr.Item("KBETR") = dtRelation.Rows(0).Item("MAT_Rate")
                            Else
                                dr.Item("data2") = dtOne.Tables(0).Rows(0).Item("KBETR")
                                dr.Item("KBETR") = dtOne.Tables(0).Rows(0).Item("KBETR") & ""
                            End If

                            dr.Item("data3") = dtTug.Rows(0).Item("Nitrogen")
                            If (LowRate = "") Then
                                dr.Item("data4") = CDbl(CDbl(dtTug.Rows(0).Item("Nitrogen")) * CDbl(dr.Item("data2"))).ToString("################0.00")
                            ElseIf (CDbl(LowRate) > CDbl(CDbl(dtTug.Rows(0).Item("Nitrogen")) * CDbl(dr.Item("data2")))) Then
                                dr.Item("data2") = CDbl(LowRate).ToString("###################0.00")
                                dr.Item("data4") = CDbl(LowRate).ToString("###################0.00")
                            Else
                                dr.Item("data4") = (CDbl(dr.Item("data2")) * CDbl(dr.Item("data3"))).ToString("#################0.00")
                            End If

                            dr.Item("New_Old") = "N"
                            dr.Item("Owner") = ""
                            dtMat.Rows.Add(dr)
                            dtMat.AcceptChanges()
                        End If

                    End If
                End If

            End If
        End If

    End Sub

    Private Sub PlusHour(ByRef Hour As Integer, ByRef Minute As Integer, ByVal P_Hour As Integer, ByVal P_Minute As Integer)
        Hour += P_Hour
        Minute += P_Minute
        If (Minute > 60) Then
            Hour += Minute / 60
            Minute = Minute Mod 60
        End If
    End Sub

    Private Sub CheckTruck(ByRef dt As DataTable)
        Dim dtTruck As DataTable = clsGet.Get_Load_Unload_Product_Bulk(ViewState("EditBooking"), "", "")




        Dim Truck6 As Integer = 0
        Dim Truck810 As Integer = 0
        Dim Trailer As Integer = 0
        Dim Trailer2 As Integer = 0
        Dim CTtruck As Boolean = True
        If (ViewState("PORT") = "B") Then
            Dim ProductTemp As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"), ViewState("SoldTo"))
            If (ProductTemp.Rows.Count > 0) Then
                For Each drr As DataRow In ProductTemp.Rows
                    For Each da As DataRow In dtTruck.Rows
                        If (da.Item("BP_CODE") = drr.Item("BP_CODE")) Then
                            Truck6 += CInt(da.Item("_Truck6"))
                            Truck810 += CInt(da.Item("_Truck810"))
                            Trailer += CInt(da.Item("_Trailer"))
                            Trailer2 += CInt(da.Item("_Trailer2"))
                        End If
                    Next
                Next

            Else
                For Each da As DataRow In dtTruck.Rows
                    Truck6 += CInt(da.Item("_Truck6"))
                    Truck810 += CInt(da.Item("_Truck810"))
                    Trailer += CInt(da.Item("_Trailer"))
                    Trailer2 += CInt(da.Item("_Trailer2"))
                Next
            End If

        Else
            For Each da As DataRow In dtTruck.Rows
                Truck6 += CInt(da.Item("_Truck6"))
                Truck810 += CInt(da.Item("_Truck810"))
                Trailer += CInt(da.Item("_Trailer"))
                Trailer2 += CInt(da.Item("_Trailer2"))
            Next
        End If

        For Each dr As DataRow In dt.Rows
            If (dr.Item("MATERIAL") = "000000002100000099") Then
                CTtruck = False
                If (Truck6 > 0) Then
                    dr.Item("data3") = Truck6
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Truck6).ToString()
                Else
                    dr.Delete()
                End If
                dt.AcceptChanges()
                Exit For
            End If
        Next
        If (Truck6 > 0) Then
            If (CTtruck) Then
                Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000099", ViewState("Plant"))
                If (dtMat.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dt.NewRow()

                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Truck6
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Truck6
                    dr.Item("data4") = CDbl(Truck6 * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dt.Rows.Add(dr)
                    dt.AcceptChanges()
                End If
            End If
        End If
        CTtruck = True
        For Each dr As DataRow In dt.Rows
            If (dr.Item("MATERIAL") = "000000002100000100") Then
                CTtruck = False
                If (Truck810 > 0) Then
                    dr.Item("data3") = Truck810
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Truck810).ToString()
                Else
                    dr.Delete()
                End If
                dt.AcceptChanges()
                Exit For
            End If
        Next
        If (Truck810 > 0) Then
            If (CTtruck) Then
                Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000100", ViewState("Plant"))
                If dtMat.Tables(0).Rows.Count > 0 Then
                    Dim dr As DataRow = dt.NewRow()

                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Truck810
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Truck810
                    dr.Item("data4") = CDbl(Truck810 * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dt.Rows.Add(dr)
                    dt.AcceptChanges()
                End If
            End If


        End If
        CTtruck = True
        For Each dr As DataRow In dt.Rows
            If (dr.Item("MATERIAL") = "000000002100000097") Then
                CTtruck = False
                If (Trailer > 0) Then
                    dr.Item("data3") = Trailer
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Trailer).ToString()
                Else
                    dr.Delete()
                End If
                dt.AcceptChanges()
                Exit For
            End If
        Next
        If (Trailer > 0) Then
            If (CTtruck) Then
                Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000097", ViewState("Plant"))
                If (dtMat.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dt.NewRow()

                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Trailer
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Trailer
                    dr.Item("data4") = CDbl(Trailer * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dt.Rows.Add(dr)
                    dt.AcceptChanges()
                End If
            End If
        End If
        CTtruck = True
        For Each dr As DataRow In dt.Rows
            If (dr.Item("MATERIAL") = "000000002100000098") Then
                CTtruck = False
                If (Trailer2 > 0) Then
                    dr.Item("data3") = Trailer2
                    dr.Item("data4") = CDbl(CDbl(dr.Item("data2")) * Trailer2).ToString()
                Else
                    dr.Delete()
                End If
                dt.AcceptChanges()
                Exit For
            End If
        Next
        If (Trailer2 > 0) Then
            If (CTtruck) Then
                Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000098", ViewState("Plant"))
                If (dtMat.Tables(0).Rows.Count > 0) Then
                    Dim dr As DataRow = dt.NewRow()

                    dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                    dr.Item("Booking_no") = ViewState("EditBooking")
                    dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                    dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                    dr.Item("Count") = Trailer2
                    dr.Item("MAT_Default") = "N"
                    dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                    dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                    dr.Item("MAT_Compute") = "Y"
                    dr.Item("MAT_Free") = "N"
                    dr.Item("data1") = ""
                    dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                    dr.Item("data3") = Trailer2
                    dr.Item("data4") = CDbl(Trailer2 * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                    dr.Item("New_Old") = "N"
                    dr.Item("Owner") = ""
                    dt.Rows.Add(dr)
                    dt.AcceptChanges()
                End If
            End If
        End If
    End Sub


    Private Function SetStructure(ByVal dv As DataTable) As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("MATERIAL", GetType(String))
        dt.Columns.Add("Booking_no", GetType(String))
        dt.Columns.Add("Text_line", GetType(String))
        dt.Columns.Add("Unit", GetType(String))
        dt.Columns.Add("Count", GetType(String))
        dt.Columns.Add("MAT_Default", GetType(String))
        dt.Columns.Add("KBETR", GetType(String))
        dt.Columns.Add("KONWA", GetType(String))
        dt.Columns.Add("MAT_Relation", GetType(String))
        dt.Columns.Add("MAT_Compute", GetType(String))
        dt.Columns.Add("MAT_Free", GetType(String))
        dt.Columns.Add("data1", GetType(String))
        dt.Columns.Add("data2", GetType(String))
        dt.Columns.Add("data3", GetType(String))
        dt.Columns.Add("data4", GetType(String))
        dt.Columns.Add("New_Old", GetType(String))
        dt.Columns.Add("Owner", GetType(String))
        dt.AcceptChanges()
        If Not (dv Is Nothing) Then
            If (dv.Rows.Count > 0) Then
                For Each dr As DataRow In dv.Rows
                    Dim dn As DataRow = dt.NewRow()

                    Dim dtable As DataSet = clsGet.Get_BookingTariff(ViewState("EditBooking"), "")
                    For Each dk As DataRow In dtable.Tables(0).Rows
                        If (dk.Item("MATERIAL") = dr.Item("MATERIAL")) Then
                            dn.Item("MATERIAL") = dr.Item("MATERIAL")
                            dn.Item("Booking_no") = dk.Item("Booking_no")
                            dn.Item("Text_line") = dk.Item("Text_line")
                            dn.Item("Unit") = dk.Item("Unit")
                            dn.Item("Count") = dk.Item("Count")
                            dn.Item("MAT_Default") = dk.Item("MAT_Default")
                            dn.Item("KBETR") = dk.Item("KBETR")
                            dn.Item("KONWA") = dk.Item("KONWA")
                            dn.Item("MAT_Relation") = dk.Item("MAT_Relation")
                            dn.Item("MAT_Compute") = dk.Item("MAT_Compute")
                            dn.Item("MAT_Free") = dk.Item("MAT_Free")
                            dn.Item("data1") = dr.Item("data1")
                            dn.Item("data2") = dr.Item("data2")
                            dn.Item("data3") = dr.Item("data3")
                            dn.Item("data4") = dr.Item("data4")
                            dn.Item("New_Old") = "O"
                            dn.Item("Owner") = ""
                            dt.Rows.Add(dn)
                            dt.AcceptChanges()
                            Exit For
                        End If
                    Next

                Next
            End If
        End If

        Return dt
    End Function

    Private Function SetMat(ByVal dt As DataTable) As DataTable

        For Each dr As DataRow In dt.Rows
            Dim data3 As String = ""
            If (dr.Item("data3") & "" = "") Then
                data3 = "0"
            Else
                data3 = dr.Item("data3")
            End If
            Dim Value As Double = CDbl(dr.Item("data2")) * CDbl(data3)
            If Not (Value.ToString("################0.00") = dr.Item("data4")) Then
                If Not (Value.ToString("################0.00") = "0.00") Then
                    dr.Item("data2") = dr.Item("data4")
                    dt.AcceptChanges()
                End If
            End If
            If Not (Value.ToString("################0.00") = dr.Item("data4")) Then
                If (Value.ToString("################0.00") = "0.00") Then
                    dr.Item("data3") = dr.Item("data1")
                    dt.AcceptChanges()
                Else
                    If (data3 <> "0") Or (data3 <> "") Then
                        dr.Item("data2") = (CDbl(dr.Item("data4")) / CDbl(data3)).ToString("###################0.00")
                    Else
                        dr.Item("data3") = "1"
                        dr.Item("data2") = dr.Item("data4")
                    End If
                    dt.AcceptChanges()
                End If
            End If
        Next

        Return dt
    End Function

    Private Function SaveTariffActual(ByVal Booking_no As String, ByRef Ret As Integer) As Boolean
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()

        tran = clsDB.BeginTran(conn)
        Ret = clsFc.InsertBookingTariff_Actual(Booking_no, conn, tran)
        If (Ret < 0) Then
            condition = False
        End If
        If (condition) Then
            clsDB.CommitTran(tran)
        Else
            clsDB.RollBackTran(tran)
        End If
        Application.UnLock()
        conn.Dispose()
        Return condition
    End Function

    Protected Sub txtData4_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim txtData4 = DirectCast(sender, TextBox)
        For i As Integer = 0 To GridMat.Rows.Count - 1
            If (txtData4.ClientID.Replace("_txtData4", "") = GridMat.Rows(i).ClientID) Then
                Dim dt As DataTable = ViewState("dtMat")
                For Each dr As DataRow In dt.Rows
                    If (dr.Item("MATERIAL") = GridMat.Rows(i).Cells(1).Text) Then
                        If (dr.Item("data3") = "") Then
                            If (dr.Item("data2") = dr.Item("data4")) Then
                                dr.Item("data2") = CDec(txtData4.Text).ToString("###############0.00")

                            ElseIf (CDbl(CDbl(dr.Item("data1")) * CDbl(dr.Item("data2"))).ToString("############0.00") = dr.Item("data4")) Then
                                dr.Item("data2") = CDbl(CDec(txtData4.Text) / CDec(dr.Item("data1"))).ToString("###############0.00")
                            Else
                                dr.Item("data2") = CDbl(CDec(txtData4.Text) / (CDec(dr.Item("data4")) / CDec(dr.Item("data2")))).ToString("#################0.00")
                            End If

                        Else
                            If (CDec(dr.Item("data2")) * CDec(dr.Item("data3"))).ToString("#############0.00") = dr.Item("data4") Then
                                dr.Item("data2") = CDbl(CDec(txtData4.Text) / CDec(dr.Item("data3"))).ToString("###############0.00")
                            ElseIf (dr.Item("data2") = dr.Item("data4")) Then
                                dr.Item("data2") = CDec(txtData4.Text).ToString("###############0.00")
                            Else
                                dr.Item("data2") = CDbl(CDec(txtData4.Text) / (CDec(dr.Item("data4")) / CDec(dr.Item("data2")))).ToString("#################0.00")
                            End If
                        End If
                        dr.Item("data4") = CDbl(txtData4.Text).ToString("###############0.00")
                        dt.AcceptChanges()
                        ViewState("dtMat") = dt
                        Exit For
                    End If
                Next
                Exit For
            End If
        Next
        Dim dtMat As DataTable = ViewState("dtMat")
        Dim c As Integer = 0
        Dim dtT As DataTable = dtMat.Copy
        For i As Integer = 0 To dtMat.Rows.Count - 1
            If (dtMat.Rows(i).Item("data4") & "" = "0.00") Then
                dtT.Rows(i - c).Delete()
                dtT.AcceptChanges()
                c += 1
            End If
        Next
        dtMat = dtT

        ViewState("dtMat") = dtMat
        GridMat.DataSource = ViewState("dtMat")
        GridMat.DataBind()

    End Sub

    Private Sub gridItem_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            'If (ViewState("Booking_OLD") & "" = gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no")) Then
            '    e.Row.Cells(0).Text = ""
            'End If
            'ViewState("Booking_OLD") = gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no")

            If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "I") Then
                    e.Row.Cells(3).Text = "Liquid(D)"
                Else
                    e.Row.Cells(3).Text = "Liquid(F)"
                End If
            Else
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "I") Then
                    e.Row.Cells(3).Text = "Bulk(D)"
                Else
                    e.Row.Cells(3).Text = "Bulk(F)"
                End If
            End If
            Try
                Dim dtLog As DataTable = clsGet.Get_Booking_LogSheet_In(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
                If (dtLog.Rows.Count > 0) Then
                    e.Row.Cells(4).Text = dtLog.Rows(0).Item("Berthing_Date") & " - " & dtLog.Rows(0).Item("Berthing_TimeTo")
                End If

                dtLog = clsGet.Get_Booking_LogSheet_Out(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
                If (dtLog.Rows.Count > 0) Then
                    e.Row.Cells(5).Text = dtLog.Rows(0).Item("Last_Date") & " - " & dtLog.Rows(0).Item("Last_Time")
                End If

            Catch ex As Exception

            End Try
            Dim imgStatus As Image = CType(e.Row.FindControl("imgStatus"), Image)
            Dim imgCredit As Image = CType(e.Row.FindControl("imgCredit"), Image)
            Dim status As String = gridItem.DataKeys(e.Row.RowIndex).Values("Status") & ""
            If (status = "F") Then
                status = "FN"
            End If
            If (status = "FN") Then
                imgStatus.ImageUrl = "~/Image/green.png"
            Else
                imgStatus.ImageUrl = "~/Image/red.png"
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Credit_Limit") & "" = "Y") Then
                imgCredit.ImageUrl = "~/Image/green.png"
            ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Credit_Limit") & "" = "N") Then
                imgCredit.ImageUrl = "~/Image/red.png"
            Else
                imgCredit.ImageUrl = "~/Image/green.png"
            End If
            Dim dt As DataTable

            dt = clsGet.Get_Booking_Product(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
            If dt.Rows.Count > 0 Then
                Dim Product As String = ""
                Dim Amount As String = "0.00"
                For Each dr As DataRow In dt.Rows
                    If (dr.Item("Product_no") & "" <> "") Then
                        If Product <> "" Then
                            Product &= ",(" & dr.Item("Product_Event") & ")" & dr.Item("Product_name")
                        Else
                            Product &= "(" & dr.Item("Product_Event") & ")" & dr.Item("Product_name")
                        End If
                        Amount = (CDbl(Amount) + CDbl(dr.Item("Product_Amount"))).ToString("##############0.00")
                    End If
                Next
                e.Row.Cells(7).Text = Product
                e.Row.Cells(8).Text = Amount
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Payin") & "" = "0") Then
                e.Row.Cells(12).Text = "C"
            Else
                e.Row.Cells(12).Text = "CR"
            End If

            Dim Owner_no As String = gridItem.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & ""
            If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                dt = clsGet.GetTemp_Estimate(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), "")
            Else
                dt = clsGet.GetTemp_Estimate(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), Owner_no)
            End If

            Dim sum As Double = 0.0
            For Each dr As DataRow In dt.Rows
                If (dr.Item("data4") & "" <> "") Then
                    ' If (Owner_no = dr.Item("Owner_Product")) Then
                    sum += CDbl(dr.Item("data4"))
                    'End If
                End If
            Next
            e.Row.Cells(13).Text = FormatNumber(sum, 2)
            If (status = "FN") Then
                If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                    dt = clsGet.GetActual_Data_Backup_For_Billing(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), "", True)
                Else
                    dt = clsGet.GetActual_Data_Backup_For_Billing(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), Owner_no, True)
                End If

                sum = 0.0
                For Each dr As DataRow In dt.Rows
                    If (dr.Item("data4") & "" <> "") Then
                        sum += CDbl(dr.Item("data4"))
                    End If
                Next
                e.Row.Cells(14).Text = FormatNumber(sum, 2)
                dt = clsGet.Get_SaleORDER_IPort_Number(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItem.DataKeys(e.Row.RowIndex).Values("Owner_Product_no"))
                If (dt.Rows.Count > 0) Then
                    Dim Biiling_no As String = ""
                    Dim Billing_noCOlor As String = ""
                    For Each db As DataRow In dt.Rows
                        Dim dSM As DataTable = clsGet.Get_SaleORDER_Material(db.Item("Iport_no"))
                        If (dSM.Rows.Count > 0) Then
                            Dim SOldto As String = ""
                            If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                                SOldto = Owner_no
                            Else
                                SOldto = dSM.Rows(0).Item("Sold_To") & ""
                            End If
                            Try
                                If (gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no").ToString.Substring(0, 1) = "B") Or (gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no").ToString.Substring(0, 1) = "S") Then
                                    SOldto = Owner_no
                                End If
                            Catch ex As Exception

                            End Try

                            If (SOldto = Owner_no) Then
                                Dim chkWP As Boolean = False
                                For Each da As DataRow In dSM.Rows
                                    If (da.Item("Material") & "" = "WP") Then
                                        chkWP = True
                                    End If
                                Next
                                If (chkWP) Then
                                    If (Billing_noCOlor <> "") Then
                                        Billing_noCOlor &= "<br />" & db.Item("EX_BILL_NO")
                                    Else
                                        Billing_noCOlor = db.Item("EX_BILL_NO") & ""
                                    End If
                                Else
                                    If (Biiling_no <> "") Then
                                        Biiling_no &= "<br />" & db.Item("EX_BILL_NO")
                                    Else
                                        Biiling_no = db.Item("EX_BILL_NO") & ""
                                    End If
                                End If
                            End If

                        Else
                            Dim SOldto As String = ""
                            If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                                SOldto = Owner_no
                            Else
                                SOldto = dSM.Rows(0).Item("Sold_To") & ""
                            End If
                            Try
                                If (gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no").ToString.Substring(0, 1) = "B") Or (gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no").ToString.Substring(0, 1) = "S") Then
                                    SOldto = Owner_no
                                End If
                            Catch ex As Exception

                            End Try
                            If (SOldto = Owner_no) Then
                                If (Biiling_no <> "") Then
                                    Biiling_no &= "<br />" & db.Item("EX_BILL_NO")
                                Else
                                    Biiling_no = db.Item("EX_BILL_NO") & ""
                                End If
                            End If

                        End If

                    Next
                    Dim lbBilling As Label = CType(e.Row.FindControl("lbBilling"), Label)
                    Dim lbBillingColor As Label = CType(e.Row.FindControl("lbBillingColor"), Label)
                    lbBilling.Text = Biiling_no
                    If (Billing_noCOlor <> "") Then
                        lbBillingColor.Text = Billing_noCOlor
                    End If
                End If
            End If
        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridItem.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridItem.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridItem.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                Next
            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridItem.PageCount.ToString()
            End If
        End If
    End Sub

    Private Sub gridItem_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridItem.RowEditing

    End Sub

    Private Sub gridTariff_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridTariff.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim txtCount As TextBox = CType(e.Row.FindControl("txtCount"), TextBox)
            If (ViewState("Payin") = "0") Then
                Dim imgdelete As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
                If (gridTariff.DataKeys(e.Row.RowIndex).Values("New_Old") = "N") Then
                    imgdelete.Visible = True
                Else
                    imgdelete.Visible = False
                End If
            End If

            If (txtCount.Text.Trim = "") Then
                txtCount.Visible = False
            Else
                txtCount.Visible = True
            End If
        End If
    End Sub

    Private Sub btnLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        Dim dtMat As DataTable = ViewState("dtMat")
        Dim ds As DataSet = Session("MAT_USE")
        For Each dr As DataRow In ds.Tables(0).Rows
            Dim drN As DataRow = dtMat.NewRow()
            drN.Item("MATERIAL") = dr.Item("MATERIAL")
            drN.Item("Text_line") = dr.Item("Text_line")
            drN.Item("Unit") = dr.Item("Unit")
            drN.Item("Count") = dr.Item("Count")
            drN.Item("MAT_Default") = dr.Item("MAT_Default")
            drN.Item("KBETR") = dr.Item("KBETR")
            drN.Item("KONWA") = dr.Item("KONWA")
            drN.Item("MAT_Relation") = dr.Item("MAT_Relation")
            drN.Item("data1") = ""
            drN.Item("data2") = dr.Item("KBETR")
            drN.Item("data3") = dr.Item("Count")
            'drN.Item("data4") = (CDbl(dr.Item("KBETR")) * CDbl(dr.Item("Count"))).ToString("################0.00")
            drN.Item("data4") = "1.00"
            drN.Item("New_Old") = "N"
            drN.Item("Owner") = ""
            drN.Item("Booking_no") = ViewState("EditBooking")
            dtMat.Rows.Add(drN)
            dtMat.AcceptChanges()
        Next

        Dim dtWharf As DataTable = clsGet.Get_BookingWharf(ViewState("EditBooking"))
        Dim Shifting As Boolean = False
        Dim BookingShifting As String = ""
        If (dtWharf.Rows.Count > 0) Then
            If (dtWharf.Rows(0).Item("Shift_Booking") & "" <> "") Then
                Shifting = True
                BookingShifting = dtWharf.Rows(0).Item("Shift_Booking")
            End If
        End If

        Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
        Dim dtLog_Out As DataTable
        If (Shifting) Then
            dtLog_Out = clsGet.Get_Booking_LogSheet_Out(BookingShifting)
        Else
            dtLog_Out = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
        End If


        Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
        If (Berthing_Date.Trim().Length < 9) Then
            Try
                Dim days As String = Berthing_Date.Substring(0, 2)
                Dim Month As String = GetNameMonth(Berthing_Date.Substring(3, 2))
                Dim Year As String = "20" & Berthing_Date.Substring(6, 2)
                Berthing_Date = days & " " & Month & " " & Year
            Catch ex As Exception

            End Try
        End If
        Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
        If (Depart_Actual_Date.Trim().Length < 9) Then
            Try
                Dim days As String = Depart_Actual_Date.Substring(0, 2)
                Dim Month As String = GetNameMonth(Depart_Actual_Date.Substring(3, 2))
                Dim Year As String = "20" & Depart_Actual_Date.Substring(6, 2)
                Depart_Actual_Date = days & " " & Month & " " & Year
            Catch ex As Exception

            End Try
        End If

        Dim ts = DateDiff("n", Berthing_Date & " " & dtActual.Rows(0).Item("Berthing_TimeFrom"), Depart_Actual_Date & " " & dtLog_Out.Rows(0).Item("Last_Time")) ' in case you need it in minutes

        Dim StartDay As Integer = CDate(ClassFunctionGetData.CDateT(Berthing_Date)).ToString("dd")
        Dim StartMonth As Integer = CDate(ClassFunctionGetData.CDateT(Berthing_Date)).ToString("MM")

        Dim StartYear As Integer = CInt(Berthing_Date.Split(" ")(2))
        Dim EndDay As Integer = CDate(ClassFunctionGetData.CDateT(Depart_Actual_Date)).ToString("dd")
        Dim EndMonth As Integer = CDate(ClassFunctionGetData.CDateT(Depart_Actual_Date)).ToString("MM")
        Dim EndYear As Integer = CInt(Depart_Actual_Date.Split(" ")(2))


        ' Dim StandartTIme As Integer = (ts / 60)
        Dim StandartTIme As Double = (ts / 60).ToString("###################.00")
        Try
            If (CInt(StandartTIme.ToString.Split(".")(1)) > 49) Then
                StandartTIme = CDbl(StandartTIme.ToString.Split(".")(0)) + 1
            ElseIf (CInt(StandartTIme.ToString.Split(".")(1)) > 0) Then
                StandartTIme = CDbl(StandartTIme.ToString.Split(".")(0)) + 0.5
            End If
        Catch ex As Exception

        End Try


        Dim Day As Integer = 0
        'If (StartYear = EndYear) Then
        If (StartMonth = EndMonth) Then
            Day = (EndDay - StartDay) + 1
        Else
            Day = ((Date.DaysInMonth(StartDay, StartMonth) - StartDay) + EndDay) + 1
        End If

        Dim GRT As String = 0.0
        Dim DWT As String = 0.0
        Dim LOA As String = 0.0
        Dim Draft As String = 0.0
        Dim Index As Integer = CInt(ViewState("IND"))
        GetValueVessel(gridItem.DataKeys(Index).Values("Vehicle_no"), GRT, LOA, DWT, Draft)
        Dim RememberRow As String = ""
        Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(ViewState("EditBooking"))
        Dim chkAgent As Boolean = True
        If (gridItem.DataKeys(Index).Values("PORT") & "" = "B") Then
            If (ViewState("SoldTo") <> dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                chkAgent = False
            End If
        End If

        For i As Integer = 0 To dtMat.Rows.Count - 1

            Dim BL As Double = 0.0
            If (gridItem.DataKeys(Index).Values("PORT") & "" = "L") Then
                Dim dtProduct As DataTable = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), "")
                If (dtProduct.Rows.Count > 0) Then
                    For Each dp As DataRow In dtProduct.Rows
                        Try
                            BL += CDbl(dp.Item("LU_BLMT"))
                        Catch ex As Exception

                        End Try
                    Next
                    dtMat.Rows(i).Item("data1") = BL
                End If
                If (Shifting) Then
                    dtProduct = clsGet.Get_Load_Unload_Product(BookingShifting, "")
                    If (dtProduct.Rows.Count > 0) Then
                        For Each dp As DataRow In dtProduct.Rows
                            Try
                                BL += CDbl(dp.Item("LU_BLMT"))
                            Catch ex As Exception

                            End Try
                        Next
                        dtMat.Rows(i).Item("data1") = BL
                    End If
                End If
            Else
                If (dtMat.Rows(i).Item("MATERIAL") & "" = "000000002100000268") Then
                    Dim dtProduct As DataTable = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), "")
                    Dim ProductTemp As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"), ViewState("SoldTo"))
                    If (dtProduct.Rows.Count > 0) Then
                        If (chkAgent) Then
                            BL = 0.0
                            Try
                                For Each drr As DataRow In dtProduct.Rows
                                    If (dtProduct.Rows(0).Item("BU_Bill") & "" = "") Then
                                        BL += CDbl(dtProduct.Rows(0).Item("BU_Manifest"))
                                    Else
                                        BL += CDbl(dtProduct.Rows(0).Item("BU_Bill"))
                                        dtMat.Rows(i).Item("data1") = CDbl(BL)
                                    End If
                                Next

                                dtMat.Rows(i).Item("data1") = CDbl(BL)
                            Catch ex As Exception

                            End Try
                        Else
                            BL = 0.0
                            Try
                                For Each drpro As DataRow In ProductTemp.Rows
                                    For Each drr As DataRow In dtProduct.Rows
                                        If (drpro.Item("BP_Code") = drr.Item("BP_Code")) Then
                                            If (drr.Item("BU_Bill") & "" = "") Then
                                                BL += CDbl(drr.Item("BU_Manifest"))
                                            Else
                                                BL += CDbl(drr.Item("BU_Bill"))
                                                dtMat.Rows(i).Item("data1") = CDbl(BL)
                                            End If
                                        End If
                                    Next
                                Next

                                dtMat.Rows(i).Item("data1") = CDbl(BL)
                            Catch ex As Exception

                            End Try
                        End If


                    End If
                    If (Shifting) Then
                        dtProduct = clsGet.Get_Load_Unload_Product(BookingShifting, "")
                        ProductTemp = clsGet.Get_Booking_Product(BookingShifting, ViewState("SoldTo"))
                        If (dtProduct.Rows.Count > 0) Then
                            If (chkAgent) Then
                                Try
                                    For Each drr As DataRow In dtProduct.Rows
                                        If (dtProduct.Rows(0).Item("BU_Bill") & "" = "") Then
                                            BL += CDbl(dtProduct.Rows(0).Item("BU_Manifest"))
                                        Else
                                            BL += CDbl(dtProduct.Rows(0).Item("BU_Bill"))
                                            dtMat.Rows(i).Item("data1") = CDbl(BL)
                                        End If
                                    Next

                                    dtMat.Rows(i).Item("data1") = CDbl(BL)
                                Catch ex As Exception

                                End Try
                            Else
                                Try
                                    For Each drpro As DataRow In ProductTemp.Rows
                                        For Each drr As DataRow In dtProduct.Rows
                                            If (drpro.Item("BP_Code") = drr.Item("BP_Code")) Then
                                                If (drr.Item("BU_Bill") & "" = "") Then
                                                    BL += CDbl(drr.Item("BU_Manifest"))
                                                Else
                                                    BL += CDbl(drr.Item("BU_Bill"))
                                                    dtMat.Rows(i).Item("data1") = CDbl(BL)
                                                End If
                                            End If
                                        Next
                                    Next

                                    dtMat.Rows(i).Item("data1") = CDbl(BL)
                                Catch ex As Exception

                                End Try
                            End If



                        End If
                    End If
                Else
                    Dim dtProduct As DataTable = clsGet.Get_Load_Unload_Product_Bulk(ViewState("EditBooking"), "", "")
                    Dim ProductTemp As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"), ViewState("SoldTo"))
                    If (dtProduct.Rows.Count > 0) Then
                        If (chkAgent) Then
                            For Each dp As DataRow In dtProduct.Rows
                                Try
                                    BL += CDbl(dp.Item("_M"))
                                Catch ex As Exception

                                End Try
                            Next
                        Else
                            For Each dp As DataRow In dtProduct.Rows
                                For Each dpro As DataRow In ProductTemp.Rows
                                    If (dp.Item("BP_CODE") = dpro.Item("BP_CODE")) Then
                                        Try
                                            BL += CDbl(dp.Item("_M"))
                                        Catch ex As Exception

                                        End Try
                                    End If
                                Next
                            Next
                        End If

                        dtMat.Rows(i).Item("data1") = BL
                    End If
                    If (Shifting) Then
                        dtProduct = clsGet.Get_Load_Unload_Product_Bulk(BookingShifting, "", "")
                        ProductTemp = clsGet.Get_Booking_Product(BookingShifting, ViewState("SoldTo"))
                        If (dtProduct.Rows.Count > 0) Then
                            If (chkAgent) Then
                                For Each dp As DataRow In dtProduct.Rows
                                    Try
                                        BL += CDbl(dp.Item("_M"))
                                    Catch ex As Exception

                                    End Try
                                Next
                            Else
                                For Each dp As DataRow In dtProduct.Rows
                                    For Each dpro As DataRow In ProductTemp.Rows
                                        If (dp.Item("BP_CODE") = dpro.Item("BP_CODE")) Then
                                            Try
                                                BL += CDbl(dp.Item("_M"))
                                            Catch ex As Exception

                                            End Try
                                        End If
                                    Next
                                Next
                            End If

                            dtMat.Rows(i).Item("data1") = BL
                        End If
                    End If
                End If


            End If
            'Check Shifting
            'If (Shifting) Then
            '    Dim dtMaterial As DataTable = clsGet.Get_MeterailAllField(dtMat.Rows(i).Item("Material") & "")
            '    Try
            '        If (dtMaterial.Rows(0).Item("MAT_Shifting") & "" <> "") Or (dtMaterial.Rows(0).Item("MAT_Shifting") & "" <> "0") Then
            '            Dim Plus As Double = CDbl(dtMaterial.Rows(0).Item("MAT_Shifting"))
            '            dtMat.Rows(i).Item("data3") = CDbl(dtMat.Rows(i).Item("data3")) + Plus
            '        End If
            '    Catch ex As Exception

            '    End Try

            'End If

            dtMat.AcceptChanges()
            Dim CNTRY As String = gridItem.DataKeys(Index).Values("Vehicle_CNTRY")
            If (CNTRY = "TH") Or (CNTRY = "T") Then
                CNTRY = "T"
            Else
                CNTRY = "O"
            End If
            Dim dtNewValue As DataTable = ComputeMoney(dtMat.Rows(i).Item("MATERIAL"), GRT, LOA, DWT, Draft, BL, ViewState("SoldTo"), gridItem.DataKeys(Index).Values("PORT") & "", StandartTIme, Day, dtMat.Rows(i).Item("data3"), gridItem.DataKeys(Index).Values("Vehicle_Destination"), CNTRY)
            If (dtNewValue.Rows.Count > 0) Then
                dtMat.Rows(i).Item("data1") = dtNewValue.Rows(0).Item("data1")
                dtMat.Rows(i).Item("data2") = dtNewValue.Rows(0).Item("data2")
                dtMat.Rows(i).Item("data3") = dtNewValue.Rows(0).Item("data3")
                dtMat.Rows(i).Item("data4") = dtNewValue.Rows(0).Item("data4")
                dtMat.AcceptChanges()
            Else
                RememberRow &= i.ToString() & "$"
            End If
        Next

        Dim c As Integer = 0
        Dim dtT As DataTable = dtMat.Copy
        For i As Integer = 0 To dtMat.Rows.Count - 1
            If (dtMat.Rows(i).Item("data4") & "" = "0.00") Then
                dtT.Rows(i - c).Delete()
                dtT.AcceptChanges()
                c += 1
            End If
        Next
        dtMat = dtT
        GridMat.PageIndex = 0
        GridMat.DataSource = dtMat
        GridMat.DataBind()
        ViewState("dtMat") = dtMat
    End Sub
    Private Sub CompleteEventNoData()
        Dim clsDB As New ClassDatabase()
        Dim clsFc As New ClassFunction()
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)
        If (ViewState("PORT") & "" = "L") Then
            If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                condition = False
            End If
        Else
            If (dsBooking.Rows(0).Item("MAgent_no") & "" <> ViewState("SoldTo") & "") Then
                If (ViewState("SoldTo") & "" <> "") Then
                    If (clsFc.UpdateBookingProduct_Status(ViewState("EditBooking"), ViewState("SoldTo") & "", "FN", conn, tran) < 1) Then
                        condition = False
                    End If
                Else
                    If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                        condition = False
                    End If
                End If

            Else
                If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                    condition = False
                End If
            End If
        End If


        If (condition) Then
            clsDB.CommitTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเสร็จสมบูรณ์');", True)
            LoadBOoking()
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึกข้อมูล ');", True)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub UpdateAgent()
        Dim Sold_to As String = ""
        Dim Sold_toname As String = ""
        Dim Bill_to As String = ""
        Dim Bill_toname As String = ""
        If (txtid.Text.Trim() <> "") Then
            Sold_to = txtid.Text.Split("-")(0)
            Sold_toname = txtid.Text.Split("-")(1)
        End If
        If (txtBillTo.Text.Trim() <> "") Then
            Bill_to = txtAgent.Text.Split("-")(0)
            Bill_toname = txtAgent.Text.Split("-")(1)
        End If

        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()

        tran = clsDB.BeginTran(conn)
        Try
            If (clsFc.UpdateBookingAgentForActual(ViewState("EditBooking"), Sold_to, Sold_toname, Bill_to, Bill_toname, conn, tran) < 1) Then
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
            Else
                clsDB.RollBackTran(tran)
            End If
        Catch ex As Exception

        End Try



    End Sub

    Private Sub btnComplete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnComplete.Click
        If (ViewState("Payin") & "" = "0") Then
            If (txtDueDate.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Due Date ');", True)
                Exit Sub
            End If
        End If

        Dim dtMat As DataTable = ViewState("dtMat")
        If rowSoldTo.Visible Then
            If (txtid.Text.Trim <> "") Then
                If ((clsGet.Get_Customer(txtid.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Sold To !!');", True)
                    Exit Sub
                Else
                    ViewState("SoldTo") = txtid.Text.Trim().Split("-")(0)
                End If
            Else
                Try
                    If (CDbl(lbNet.Text) > 0) Then
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Sold To !!');", True)
                        Exit Sub
                    Else
                        rowSoldTo.Visible = False
                    End If
                Catch ex As Exception

                End Try

            End If
            If (txtBillTo.Text.Trim <> "") Then
                If ((clsGet.Get_Customer(txtBillTo.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Bill To !!');", True)
                    Exit Sub
                Else
                    ViewState("BillTo") = txtBillTo.Text.Trim().Split("-")(0)
                End If
            Else
                ViewState("BillTo") = txtid.Text.Trim().Split("-")(0)
            End If
            UpdateAgent()
        End If

        ' If (ViewState("PORT") & "" = "B") Then
        If (ViewState("EditBooking").ToString.Substring(0, 1) <> "B") Then
            If (ViewState("EditBooking").ToString.Substring(0, 1) <> "S") Then
                Dim dtTemp As DataTable = dtMat.Clone
                For i As Integer = 0 To GridMat.Rows.Count - 1
                    Dim chk As CheckBox = CType(GridMat.Rows(i).FindControl("chk"), CheckBox)
                    If (chk.Checked) Then
                        dtTemp.ImportRow(dtMat.Rows(i))
                        dtTemp.AcceptChanges()
                    End If
                Next
                dtMat = dtTemp
                ViewState("dtMat") = dtMat
            End If
        End If
        If (dtMat.Rows.Count = 0) Then
            CompleteEventNoData()
            Exit Sub
        End If
        ' End If
        If (ViewState("Payin") = "0") Then
            'Cash Sale สร้าง CNDN
            'If (ViewState("PORT") = "L") Then
            'Liquid
            dtMat = SetMat(dtMat)
            If Not (clsGet.GetPayinAdvance(ViewState("EditBooking"), ViewState("SoldTo"))) Then
                Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(ViewState("EditBooking"))
                Dim Remark As String = ""
                If (dsBooking.Tables(0).Rows.Count > 0) Then
                    Remark = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                    Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
                    Dim dtWharf As DataTable = clsGet.Get_BookingWharf(ViewState("EditBooking"))
                    Dim Shifting As Boolean = False
                    Dim BookingShifting As String = ""
                    If (dtWharf.Rows.Count > 0) Then
                        If (dtWharf.Rows(0).Item("Shift_Booking") & "" <> "") Then
                            Shifting = True
                            BookingShifting = dtWharf.Rows(0).Item("Shift_Booking")
                        End If
                    End If
                    Dim dtLog_Out As DataTable
                    If (Shifting) Then
                        dtLog_Out = clsGet.Get_Booking_LogSheet_Out(BookingShifting)
                    Else
                        dtLog_Out = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
                    End If
                    If (dtActual.Rows.Count > 0) And (dtLog_Out.Rows.Count > 0) Then
                        Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
                        Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
                        Remark &= " " & Berthing_Date & " - " & Depart_Actual_Date
                    End If

                End If
                CreateCNDN_Advanced_Payment(dtMat, Remark)
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ลูกค้ายังไม่ได้ทำการชำระเงิน  ');", True)
                Exit Sub
            End If

        Else
            'Credit Sale  ทำการ Change Order และทำการออก Billing

            'If (ViewState("PORT") = "L") Then
            dtMat = SetMat(dtMat)
            If (Change_Order(dtMat, ViewState("SoldTo"))) Then
                'ทำการสร้าง Billing
                Create_Biling()
            End If

        End If
    End Sub

    Private Function dtIportNumbet() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("Iport_no", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub Create_Biling()
        Dim dtIport_Number As DataTable = clsGet.Get_SaleORDER_IPort_Number(ViewState("EditBooking"), ViewState("SoldTo"))
        For Each dr As DataRow In dtIport_Number.Rows
            If (dr.Item("Credit_Limit") = "N") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Document cannot be billed due to credit limit check  ');", True)
                Exit Sub
            End If
        Next
        Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
        Dim ClassSAP As New Class_SAP
        Dim dtOut As DataTable = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))

        Dim Bill_Date As String = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))
        If (txtDate.Text.Trim() <> "") Then
            Try
                Bill_Date = txtDate.Text.Split(" ")(2) & CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("MMdd")
            Catch ex As Exception

            End Try
        End If
        'If (dtOut.Rows.Count > 0) Then
        '    Try
        '        Bill_Date = dtOut.Rows(0).Item("Last_Date").ToString.Split(" ")(2) & CDate(dtOut.Rows(0).Item("Last_Date")).ToString("MMdd")
        '        Bill_Date = Bill_Date.Trim()
        '    Catch ex As Exception
        '        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลเรือออกไม่ถูกต้องกรุณาสอบถามเจ้าหน้าที่ PTMM ');", True)
        '        Exit Sub
        '    End Try
        'Else
        '    Bill_Date = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))
        'End If

        Dim Date_Click As String = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))
        If (dtIport_Number.Rows.Count > 0) Then
            For Each dr As DataRow In dtIport_Number.Rows
                Dim EX_SALES_NO As String = ""
                Dim EX_BILL_NO As String = ""
                Dim EX_BUKRS As String = ""
                Dim EX_BELNR As String = ""
                Dim EX_GJAHR As String = ""
                Try
                    Dim Berth_UnBerth As String = ""
                    Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
                    Dim dtLog_Out As DataTable = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
                    If (dtActual.Rows.Count > 0) And (dtLog_Out.Rows.Count > 0) Then
                        Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
                        Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
                        Berth_UnBerth = Berthing_Date & " - " & Depart_Actual_Date
                    End If
                    Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
                    Dim BABIHEADER As New SAP_IPORT.ZBAPI_SALES_HEADER
                    BABIHEADER.Berth = Berth_UnBerth


                    Dim BABIONETIME As New SAP_IPORT.ZBAPI_SALES_ONETIME
                    Dim dtOther As DataTable = clsGet.Get_OtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1))
                    If (dtOther.Rows.Count > 0) Then
                        If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                            BABIHEADER.Pmnttrms = "D015"
                        End If
                        If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                            If (dtOther.Rows(0).Item("Customer_name").ToString.Length < 40) Then
                                BABIONETIME.Name = dtOther.Rows(0).Item("Customer_name")
                            ElseIf (dtOther.Rows(0).Item("Customer_name").ToString.Length < 80) Then
                                BABIONETIME.Name = dtOther.Rows(0).Item("Customer_name").ToString.Substring(0, 39)
                                BABIONETIME.Name_2 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(40, dtOther.Rows(0).Item("Customer_name").ToString.Length - 1)
                            Else
                                BABIONETIME.Name = dtOther.Rows(0).Item("Customer_name").ToString.Substring(0, 39)
                                BABIONETIME.Name_2 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(40, 79)
                                BABIONETIME.Name_3 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(80, dtOther.Rows(0).Item("Customer_name").ToString.Length - 1)
                            End If
                            BABIONETIME.City = dtOther.Rows(0).Item("City")
                            BABIONETIME.District = dtOther.Rows(0).Item("District")
                            BABIONETIME.Location = dtOther.Rows(0).Item("Location")
                            BABIONETIME.Postl_Cod1 = dtOther.Rows(0).Item("Postal_Code")
                            BABIONETIME.Str_Suppl3 = dtOther.Rows(0).Item("Str_Sup")
                            BABIONETIME.Street = dtOther.Rows(0).Item("Street")
                        End If
                    End If


                    Dim SALE_TABLE As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
                    Dim BABITable As New SAP_IPORT.BAPIRET1Table

                    SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "", dr.Item("Iport_no"), BABIONETIME, BABIHEADER, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE)
                    ClassSAP.SAP_CLOSE(SAP_Data)
                    If (EX_BILL_NO <> "") Then
                        Dim clsDB As New ClassDatabase()
                        Dim clsFc As New ClassFunction()
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Application.Lock()
                        conn.Open()
                        tran = clsDB.BeginTran(conn)
                        If (ViewState("EditBooking").ToString.Substring(0, 1) = "B") Or (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
                            If (clsFc.UPDATESale_Order(ViewState("EditBooking"), dr.Item("Iport_no"), EX_SALES_NO, EX_BILL_NO, EX_BUKRS, EX_BELNR, EX_GJAHR, Date_Click, conn, tran) < 1) Then
                                condition = False
                            End If
                        Else
                            If (clsFc.UPDATEBooking_Credit_limit(ViewState("EditBooking"), conn, tran) > 0) Then
                                If (clsFc.UPDATESale_Order(ViewState("EditBooking"), dr.Item("Iport_no"), EX_SALES_NO, EX_BILL_NO, EX_BUKRS, EX_BELNR, EX_GJAHR, Date_Click, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If
                        End If


                        For Each db As SAP_IPORT.BAPIRET1 In BABITable
                            If (clsFc.InsertSAP_Table_MESSAGE(dr.Item("Iport_no"), "Zbapi_Iport_Sd_Proc_Cash_Sales", db.Type, db.Id, db.Number, db.Message, db.Log_No, db.Log_Msg_No, db.Message_V1, db.Message_V2, db.Message_V3, db.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (ViewState("EditBooking").ToString.Substring(0, 1) = "B") Then
                            If (clsFc.UpdateBooking_Bas_Vessel(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1), "F", "", "", "", "", "", conn, tran) < 1) Then
                                condition = False
                            End If
                        ElseIf (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
                            If (clsFc.UpdateOtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1), "F", conn, tran) < 1) Then
                                condition = False
                            End If
                        Else

                            If (ViewState("PORT") & "" = "L") Then
                                If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                                    condition = False
                                End If
                            Else
                                If (dsBooking.Rows(0).Item("MAgent_no") & "" <> ViewState("SoldTo") & "") Then
                                    If (clsFc.UpdateBookingProduct_Status(ViewState("EditBooking"), ViewState("SoldTo") & "", "FN", conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Else
                                    If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                                        condition = False
                                    End If
                                End If
                            End If
                        End If

                        Dim dtMat As DataTable = ViewState("dtMat")
                        If (ViewState("PORT") & "" = "B") Then
                            clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), ViewState("SoldTo"), conn, tran)
                        Else
                            clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", conn, tran)
                        End If

                        For Each dm As DataRow In dtMat.Rows
                            If (clsFc.InsertActual_Data_Backup_For_Billing(dm.Item("MATERIAL"), ViewState("EditBooking"), dm.Item("Text_line"), dm.Item("Unit"), dm.Item("Count"), dm.Item("MAT_Default"), dm.Item("KBETR"), dm.Item("KONWA"), dm.Item("MAT_Relation"), dm.Item("MAT_Compute"), dm.Item("MAT_Free"), dm.Item("data1"), dm.Item("data2"), dm.Item("data3"), dm.Item("data4"), "O", "Y", ViewState("SoldTo"), conn, tran) < 1) Then
                                condition = False
                            End If
                        Next

                        If (condition) Then
                            clsDB.CommitTran(tran)
                            SendMail(ViewState("EditBooking"), GenBody("รายละเอียดค่าใช้บริการในท่าเรือรายการ Booking No. : " & ViewState("EditBooking")))
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการสร้าง Billing เสร็จสมบูรณ์ ');", True)
                            LoadBOoking()
                        Else
                            clsDB.RollBackTran(tran)
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
                        End If
                        Application.UnLock()
                        conn.Dispose()
                    Else
                        Dim Message As String = ""
                        For Each dh As SAP_IPORT.BAPIRET1 In BABITable
                            Message &= dh.Message
                        Next
                        ViewState("MessageSAP") = Message
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & Message & "');", True)
                        Exit Sub
                    End If
                Catch ex As Exception
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
                    Exit Sub
                End Try
            Next
        Else
            Dim clsDB As New ClassDatabase()
            Dim clsFc As New ClassFunction()
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Application.Lock()
            conn.Open()
            tran = clsDB.BeginTran(conn)

            If (ViewState("EditBooking").ToString.Substring(0, 1) = "B") Then
                If (clsFc.UpdateBooking_Bas_Vessel(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1), "F", "", "", "", "", "", conn, tran) < 1) Then
                    condition = False
                End If
            ElseIf (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
                If (clsFc.UpdateOtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1), "F", conn, tran) < 1) Then
                    condition = False
                End If
            Else

                If (ViewState("PORT") & "" = "L") Then
                    If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                        condition = False
                    End If
                Else
                    If (dsBooking.Rows(0).Item("MAgent_no") & "" <> ViewState("SoldTo") & "") Then
                        If (clsFc.UpdateBookingProduct_Status(ViewState("EditBooking"), ViewState("SoldTo") & "", "FN", conn, tran) < 1) Then
                            condition = False
                        End If
                    Else
                        If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                            condition = False
                        End If
                    End If
                End If
            End If

            Dim dtMat As DataTable = ViewState("dtMat")
            If (ViewState("PORT") & "" = "B") Then
                clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), ViewState("SoldTo"), conn, tran)
            Else
                clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", conn, tran)
            End If

            For Each dm As DataRow In dtMat.Rows
                If (clsFc.InsertActual_Data_Backup_For_Billing(dm.Item("MATERIAL"), ViewState("EditBooking"), dm.Item("Text_line"), dm.Item("Unit"), dm.Item("Count"), dm.Item("MAT_Default"), dm.Item("KBETR"), dm.Item("KONWA"), dm.Item("MAT_Relation"), dm.Item("MAT_Compute"), dm.Item("MAT_Free"), dm.Item("data1"), dm.Item("data2"), dm.Item("data3"), dm.Item("data4"), "O", "Y", ViewState("SoldTo"), conn, tran) < 1) Then
                    condition = False
                End If
            Next

            If (condition) Then
                clsDB.CommitTran(tran)

                SendMail(ViewState("EditBooking"), GenBody("รายละเอียดค่าใช้บริการในท่าเรือรายการ Booking No. : " & ViewState("EditBooking")))
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการ Confirm Actual เสร็จสมบูรณ์ ');", True)
                LoadBOoking()
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึกข้อมูล ');", True)
            End If
            Application.UnLock()
            conn.Dispose()
        End If

    End Sub

    Private Function AddRow(ByVal dtChange As DataTable, ByVal dr As DataRow, ByVal Z01 As String, ByVal Z02 As String, ByVal Z03 As String, ByVal CLear As String) As DataTable
        Dim dn As DataRow = dtChange.NewRow
        dn.Item("Material") = dr.Item("Material")
        dn.Item("Booking_no") = dr.Item("Booking_no")
        dn.Item("Text_line") = dr.Item("Text_line")
        dn.Item("Unit") = dr.Item("Unit")
        dn.Item("Count") = dr.Item("Count")
        dn.Item("Mat_Default") = dr.Item("Mat_Default")
        dn.Item("KBETR") = dr.Item("KBETR")
        dn.Item("KONWA") = dr.Item("KONWA")
        dn.Item("MAT_Relation") = dr.Item("MAT_Relation")
        dn.Item("MAT_Compute") = dr.Item("MAT_Compute")
        dn.Item("MAT_Free") = dr.Item("MAT_Free")
        dn.Item("data1") = dr.Item("data1")
        dn.Item("data2") = dr.Item("data2")
        If (CLear = "X") Then
            dn.Item("data3") = CDbl(dr.Item("data3")) * 2
        Else
            dn.Item("data3") = dr.Item("data3")
        End If

        dn.Item("data4") = dr.Item("data4")
        dn.Item("Z01") = Z01
        dn.Item("Z02") = Z02
        dn.Item("Z03") = Z03
        dtChange.Rows.Add(dn)
        dtChange.AcceptChanges()
        Return dtChange
    End Function

    Private Sub CreateCNDN_Advanced_Payment(ByVal dtMat As DataTable, ByVal Remark As String)
        Dim dtMatOriginal As DataTable
        If (ViewState("PORT") = "L") Then
            dtMatOriginal = clsGet.GetBookingTariff_Actual(ViewState("EditBooking"), "", "")
        Else
            dtMatOriginal = clsGet.GetBookingTariff_Actual(ViewState("EditBooking"), "", ViewState("SoldTo"))
        End If

        Dim dtChange As DataTable = dtMatOriginal.Clone
        dtChange.Columns.Add("Z01", GetType(String))
        dtChange.Columns.Add("Z02", GetType(String))
        dtChange.Columns.Add("Z03", GetType(String))
        dtChange.AcceptChanges()
        dtChange.Rows.Clear()
        dtChange.AcceptChanges()

        Dim BABI_SALE11 As New SAP_IPORT.ZBAPI_SALES_ITEMS
        Dim BABI_SALE12 As New SAP_IPORT.ZBAPI_SALES_ITEMS

        Dim SALE_TABLE11_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE11_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE11_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable


        Dim SALE_TABLE12_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE12_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE12_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable

        Dim MaterialChange As String = "''"
        Dim MaterialInvoice As String = "''"
        Dim Plant As String = "1104"
        ' Dim dtMatEstimate As DataSet
        If (ViewState("PORT") = "L") Then
            Plant = "1103"
            'dtMatEstimate = clsGet.Get_BookingTariff(ViewState("EditBooking"), "")
        Else
            'dtMatEstimate = clsGet.Get_BookingTariff(ViewState("EditBooking"), ViewState("SoldTo"))
        End If
        'For Each dr As DataRow In dtMat.Rows
        '    Dim chkNEW_Old = True
        '    For Each dx As DataRow In dtMatEstimate.Tables(0).Rows
        '        If (dr.Item("Material") = dx.Item("Material")) Then
        '            dr.Item("New_Old") = "O"
        '            chkNEW_Old = False
        '            Exit For
        '        End If
        '    Next
        '    If (chkNEW_Old) Then
        '        dr.Item("New_Old") = "N"
        '    End If
        '    dtMat.AcceptChanges()
        'Next
        Dim condition11 As Boolean = False
        Dim condition12 As Boolean = False
        For Each dr As DataRow In dtMat.Rows
            If (dr.Item("New_Old") = "O") Then
                'รายการเก่าทำการตรวจสอบยอดและ Rate
                For Each drO As DataRow In dtMatOriginal.Rows
                    If (dr.Item("Material") = drO.Item("Material")) Then
                        'Check เปลี่ยนราคาไหม
                        Dim Z01 As String = ""
                        Dim Z02 As String = ""
                        Dim Z03 As String = ""
                        Dim Unit As String = drO.Item("Unit") & ""
                        Dim Chk As Boolean = True
                        For x As Integer = 0 To Unit.Split("/").Length - 1
                            If (Unit.Split("/")(x).ToUpper = "JOB") Then
                                Chk = False
                            End If
                        Next
                        If (Chk) Then
                            ' NOt JOB
                            If (CDbl(dr.Item("data2")) > CDbl(drO.Item("data2"))) Then
                                'ใหม่มากกว่าเก่า ZDR  Z02
                                Z02 = "ZDR"
                            ElseIf (CDbl(dr.Item("data2")) < CDbl(drO.Item("data2"))) Then
                                'ใหม่น้อยกว่าเก่า ZCR Z01
                                Z01 = "ZCR"
                            End If
                            If (dr.Item("data3") & "" <> "") And (drO.Item("data3") & "" <> "") Then
                                'Check เปลี่ยน Quatity ไหม
                                If (CDbl(dr.Item("data3")) > CDbl(drO.Item("data3"))) Then
                                    'ใหม่มากกว่าเก่า ZDR Z03
                                    Z03 = "ZDR"
                                ElseIf (CDbl(dr.Item("data3")) < CDbl(drO.Item("data3"))) Then
                                    'ใหม่น้อยกว่าเก่า ZCR Z03
                                    Z03 = "ZCR"
                                End If
                            End If
                        Else
                            'Not JOB
                            If (CDbl(dr.Item("data4")) > CDbl(drO.Item("data4"))) Then
                                'ใหม่มากกว่าเก่า ZDR  Z02
                                Z02 = "ZDR"
                            ElseIf (CDbl(dr.Item("data4")) < CDbl(drO.Item("data4"))) Then
                                'ใหม่น้อยกว่าเก่า ZCR Z01
                                Z01 = "ZCR"
                            End If
                        End If

                        If (Z01 <> "") Or (Z02 <> "") Or (Z03 <> "") Then
                            dtChange = AddRow(dtChange, dr, Z01, Z02, Z03, "")
                            MaterialChange &= ",'" & dr.Item("Material") & "'"
                        End If
                        Exit For
                    End If
                Next
            Else
                'กรณีสร้าง Invoid ใหม่เนื่องจากเป็น Mat ที่เพิ่มมาใหม่
                MaterialInvoice &= ",'" & dr.Item("Material") & "'"
                Dim dt As DataTable = clsGet.GetMaterialAllByOne(dr.Item("Material"))
                Dim Target_QU As String = clsGet.GetBASE_UOM_FromMaterial(dr.Item("Material"))
                Dim Target_Qty As String = ""
                Dim Amount As String = ""
                If (Target_QU = "JOB") Then
                    Target_Qty = "1"
                    Amount = dr.Item("data4")
                Else
                    Target_Qty = dr.Item("data3")
                    Amount = dr.Item("data2")
                End If
                If (dt.Rows(0).Item("Division") & "" = "11") Then
                    ' Dim MAT_FOR As String = clsGet.GetMAT_FOR_FromMaterial(dr.Item("Material"))
                    BABI_SALE11 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE11.Material = dr.Item("Material")
                    BABI_SALE11.Plant = Plant
                    BABI_SALE11.Target_Qty = Target_Qty
                    BABI_SALE11.Target_Qu = Target_QU
                    BABI_SALE11.Cond_Type = ""
                    BABI_SALE11.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE11.Amount = LowRate
                            BABI_SALE11.Condvalue = LowRate
                        Else
                            BABI_SALE11.Amount = Amount
                            BABI_SALE11.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE11.Amount = Amount
                        BABI_SALE11.Condvalue = "0"
                    End Try
                    ' If (MAT_FOR = "A") Then
                    If (dt.Rows(0).Item("TAXCLASS") & "" = "0") Then
                        SALE_TABLE11_0.Insert(0, BABI_SALE11)
                    ElseIf (dt.Rows(0).Item("TAXCLASS") & "" = "1") Then
                        SALE_TABLE11_1.Insert(0, BABI_SALE11)
                    ElseIf (dt.Rows(0).Item("TAXCLASS") & "" = "5") Then
                        SALE_TABLE11_5.Insert(0, BABI_SALE11)
                    End If
                    condition11 = True
                ElseIf (dt.Rows(0).Item("Division") & "" = "12") Then
                    '  Dim MAT_FOR As String = clsGet.GetMAT_FOR_FromMaterial(dr.Item("Material"))
                    BABI_SALE12 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE12.Material = dr.Item("Material")
                    BABI_SALE12.Plant = Plant
                    BABI_SALE12.Target_Qty = Target_Qty
                    BABI_SALE12.Target_Qu = Target_QU
                    BABI_SALE12.Cond_Type = ""
                    BABI_SALE12.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE12.Amount = LowRate
                            BABI_SALE12.Condvalue = LowRate
                        Else
                            BABI_SALE12.Amount = Amount
                            BABI_SALE12.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE12.Amount = Amount
                        BABI_SALE12.Condvalue = "0"
                    End Try
                    If (dt.Rows(0).Item("TAXCLASS") & "" = "0") Then
                        SALE_TABLE12_0.Insert(0, BABI_SALE12)
                    ElseIf (dt.Rows(0).Item("TAXCLASS") & "" = "1") Then
                        SALE_TABLE12_1.Insert(0, BABI_SALE12)
                    ElseIf (dt.Rows(0).Item("TAXCLASS") & "" = "5") Then
                        SALE_TABLE12_5.Insert(0, BABI_SALE12)
                    End If
                    condition12 = True
                End If
            End If
        Next
        For Each drO As DataRow In dtMatOriginal.Rows
            Dim notFound As Boolean = True
            For Each dr As DataRow In dtMat.Rows
                If (dr.Item("Material") = drO.Item("Material")) Then
                    notFound = False
                    Exit For
                End If
            Next
            If (notFound) Then
                dtChange = AddRow(dtChange, drO, "", "", "ZCR", "X")
                MaterialChange &= ",'" & drO.Item("Material") & "'"
            End If
        Next

        Dim dtCNDN As DataTable
        If (ViewState("PORT") = "L") Then
            dtCNDN = clsGet.GetOrderFor_CreateCNDN(ViewState("EditBooking"), MaterialChange, "")
        Else
            dtCNDN = clsGet.GetOrderFor_CreateCNDN(ViewState("EditBooking"), MaterialChange, ViewState("SoldTo"))
        End If

        If (dtCNDN.Rows.Count > 0) Then

            '************************************************************
            Dim CheckCompleteAll As Boolean = True
            Dim Credit_Limit As Boolean = True
            Dim ClassSAP As New Class_SAP
            Dim SAP_Data As Object
            'ทำการสร้าง Z03 ZDR
            Dim Sold_To As String = ViewState("SoldTo")
            Dim First As Boolean = False
            Dim ZBABI_RET As New SAP_IPORT.BAPIRET1Table
            Dim CNDN_TABLE As New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
            Dim CNDN As New SAP_IPORT.ZBAPI_CN_DN_ITEMS
            Dim Doc_TYPE As String = ""
            Dim Iport_Number As String = clsGet.Get_IportNumber()
            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) - 1).ToString("000")
            Dim Reason As String = ""
            Dim REF_DOC As String = ""
            Dim Old_Iport_no As String = ""
            Dim EX_Sale As String = ""
            Dim Due_Date As String = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))


            ZBABI_RET = New SAP_IPORT.BAPIRET1Table
            CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
            CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
            For Each dr As DataRow In dtCNDN.Rows
                If (dr.Item("Sold_To") = Sold_To) Then
                    First = True

                    Doc_TYPE = "ZDR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z03"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z03") = "ZDR") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                Else
                                    CNDN.Target_Qty = (CDbl(dn.Item("data3")) - CDbl(dr.Item("Target_Qty"))).ToString("################0.000")
                                End If

                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"
                                CNDN.Amount = dr.Item("Amount")
                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                Else
                    If (First) Then
                        If (CNDN_TABLE.Count > 0) Then
                            System.Threading.Thread.Sleep(1000)
                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            If (EX_Sale <> "") Then
                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                                        For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                            If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                                condition = False
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                End If
                            End If
                            For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                                If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False


                            End If
                            Application.UnLock()
                            conn.Dispose()
                            CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
                        End If
                    End If
                    Sold_To = dr.Item("Sold_To")

                    First = True
                    ZBABI_RET = New SAP_IPORT.BAPIRET1Table
                    CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                    Doc_TYPE = "ZDR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z03"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z03") = "ZDR") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                Else
                                    CNDN.Target_Qty = (CDbl(dn.Item("data3")) - CDbl(dr.Item("Target_Qty"))).ToString("################0.000")
                                End If

                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"
                                CNDN.Amount = dr.Item("Amount")
                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                End If

            Next

            If (CNDN_TABLE.Count > 0) Then
                System.Threading.Thread.Sleep(1000)
                SAP_Data = ClassSAP.SAP_OPEN()
                Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                ClassSAP.SAP_CLOSE(SAP_Data)

                Dim Mess As String = ""
                For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                    Mess &= dv.Message
                Next

                Dim clsDB As New ClassDatabase()
                Dim clsFc As New ClassFunction()
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                If (EX_Sale <> "") Then
                    If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                        If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                            For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                        Else
                            condition = False
                        End If
                    End If
                End If
                For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                        condition = False
                    End If
                Next
                If (condition) Then
                    clsDB.CommitTran(tran)
                Else
                    clsDB.RollBackTran(tran)
                    CheckCompleteAll = False
                End If
                Application.UnLock()
                conn.Dispose()
            End If

            '************************************************************

            'ทำการสร้าง Z03 ZCR

            System.Threading.Thread.Sleep(1500)
            ZBABI_RET = New SAP_IPORT.BAPIRET1Table
            CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
            CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
            First = False
            For Each dr As DataRow In dtCNDN.Rows
                If (dr.Item("Sold_To") = Sold_To) Then
                    First = True

                    Doc_TYPE = "ZCR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z03"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z03") = "ZCR") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                Else
                                    Dim Tartget As String = ""
                                    If (CDbl(dn.Item("data3")) > CDbl(dr.Item("Target_Qty"))) Then
                                        Tartget = (CDbl(dn.Item("data3")) - CDbl(dr.Item("Target_Qty"))).ToString("################0.000")
                                    Else
                                        Tartget = (CDbl(dr.Item("Target_Qty")) - CDbl(dn.Item("data3"))).ToString("################0.000")
                                    End If
                                    CNDN.Target_Qty = Tartget
                                End If

                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"
                                CNDN.Amount = dr.Item("Amount")
                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                Else
                    If (First) Then
                        If (CNDN_TABLE.Count > 0) Then
                            System.Threading.Thread.Sleep(1000)
                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            If (EX_Sale <> "") Then
                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                                        For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                            If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                                condition = False
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                End If
                            End If
                            For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                                If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()

                            CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
                        End If
                    End If
                    Sold_To = dr.Item("Sold_To")

                    First = True
                    ZBABI_RET = New SAP_IPORT.BAPIRET1Table
                    CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                    Doc_TYPE = "ZCR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z03"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z03") = "ZCR") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                Else
                                    Dim Tartget As String = ""
                                    If (CDbl(dn.Item("data3")) > CDbl(dr.Item("Target_Qty"))) Then
                                        Tartget = (CDbl(dn.Item("data3")) - CDbl(dr.Item("Target_Qty"))).ToString("################0.000")
                                    Else
                                        Tartget = (CDbl(dr.Item("Target_Qty")) - CDbl(dn.Item("data3"))).ToString("################0.000")
                                    End If
                                    CNDN.Target_Qty = Tartget
                                End If
                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"
                                CNDN.Amount = dr.Item("Amount")
                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                End If

            Next

            If (CNDN_TABLE.Count > 0) Then
                System.Threading.Thread.Sleep(1000)
                SAP_Data = ClassSAP.SAP_OPEN()
                Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                ClassSAP.SAP_CLOSE(SAP_Data)

                Dim xx As String = ""
                For Each dr As SAP_IPORT.BAPIRET1 In ZBABI_RET
                    xx = "<br />" & dr.Message
                Next

                Dim clsDB As New ClassDatabase()
                Dim clsFc As New ClassFunction()
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)

                If (EX_Sale <> "") Then
                    If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                        If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                            For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                        Else
                            condition = False
                        End If
                    End If
                End If
                For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                        condition = False
                    End If
                Next
                If (condition) Then
                    clsDB.CommitTran(tran)
                Else
                    clsDB.RollBackTran(tran)
                    CheckCompleteAll = False
                End If
                Application.UnLock()
                conn.Dispose()

            End If

            '*********************************************************
            'ทำการสร้าง Z01

            System.Threading.Thread.Sleep(1500)
            ZBABI_RET = New SAP_IPORT.BAPIRET1Table
            CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
            CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
            First = False
            For Each dr As DataRow In dtCNDN.Rows
                If (dr.Item("Sold_To") = Sold_To) Then
                    First = True

                    Doc_TYPE = "ZCR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z01"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z01") <> "") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                    CNDN.Amount = (CDbl(dr.Item("Amount")) - CDbl(dn.Item("data4"))).ToString("################0.00")
                                Else
                                    CNDN.Target_Qty = dn.Item("data3")
                                    CNDN.Amount = (CDbl(dr.Item("Amount")) - CDbl(dn.Item("data2"))).ToString("################0.00")
                                End If

                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"  'ZNET

                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                Else
                    If (First) Then
                        If (CNDN_TABLE.Count > 0) Then
                            System.Threading.Thread.Sleep(1000)
                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            If (EX_Sale <> "") Then
                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                                        For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                            If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                                condition = False
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                End If
                            End If
                            For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                                If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()

                        End If
                    End If
                    Sold_To = dr.Item("Sold_To")

                    First = True
                    ZBABI_RET = New SAP_IPORT.BAPIRET1Table
                    CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
                    CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                    Doc_TYPE = "ZCR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z01"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z01") <> "") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                    CNDN.Amount = (CDbl(dr.Item("Amount")) - CDbl(dn.Item("data4"))).ToString("################0.00")
                                Else
                                    CNDN.Target_Qty = dn.Item("data3")
                                    CNDN.Amount = (CDbl(dr.Item("Amount")) - CDbl(dn.Item("data2"))).ToString("################0.00")
                                End If

                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"  'ZNET

                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                End If

            Next

            If (CNDN_TABLE.Count > 0) Then
                System.Threading.Thread.Sleep(1000)
                SAP_Data = ClassSAP.SAP_OPEN()
                Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                ClassSAP.SAP_CLOSE(SAP_Data)

                Dim clsDB As New ClassDatabase()
                Dim clsFc As New ClassFunction()
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                If (EX_Sale <> "") Then
                    If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                        If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                            For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                        Else
                            condition = False
                        End If
                    End If
                End If
                For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                        condition = False
                    End If
                Next
                If (condition) Then
                    clsDB.CommitTran(tran)
                Else
                    clsDB.RollBackTran(tran)
                    CheckCompleteAll = False
                End If
                Application.UnLock()
                conn.Dispose()

            End If


            '***********************************************

            'ทำการสร้าง Z02

            System.Threading.Thread.Sleep(1500)
            ZBABI_RET = New SAP_IPORT.BAPIRET1Table
            CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
            CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
            First = False
            For Each dr As DataRow In dtCNDN.Rows
                If (dr.Item("Sold_To") = Sold_To) Then
                    First = True

                    Doc_TYPE = "ZDR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z02"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z02") <> "") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                    CNDN.Amount = (CDbl(dn.Item("data4")) - CDbl(dr.Item("Amount"))).ToString("################0.00")
                                Else
                                    CNDN.Target_Qty = dn.Item("data3")
                                    CNDN.Amount = (CDbl(dn.Item("data2")) - CDbl(dr.Item("Amount"))).ToString("################0.00")
                                End If

                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"  'ZNET

                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                Else
                    If (First) Then
                        If (CNDN_TABLE.Count > 0) Then
                            System.Threading.Thread.Sleep(1000)
                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            If (EX_Sale <> "") Then
                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                                        For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                            If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                                condition = False
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                End If
                            End If
                            For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                                If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()

                        End If
                    End If
                    Sold_To = dr.Item("Sold_To")

                    First = True
                    ZBABI_RET = New SAP_IPORT.BAPIRET1Table
                    CNDN_TABLE = New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
                    CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                    Doc_TYPE = "ZDR"
                    Old_Iport_no = dr.Item("Iport_no")

                    Reason = "Z02"
                    REF_DOC = dr.Item("EX_BILL_NO")

                    EX_Sale = ""
                    Due_Date = DateTime.Now.AddDays(CInt(txtDueDate.Text)).ToString("yyyyMMdd", New Globalization.CultureInfo("en-US"))
                    For Each dn As DataRow In dtChange.Rows
                        If (dn.Item("Z02") <> "") Then
                            If (dr.Item("Material") = dn.Item("Material")) Then
                                CNDN = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                                CNDN.Material = dr.Item("Material")
                                CNDN.Plant = Plant
                                If (dr.Item("Target_Qu") & "" = "JOB") Then
                                    CNDN.Target_Qty = "1"
                                    CNDN.Amount = (CDbl(dn.Item("data4")) - CDbl(dr.Item("Amount"))).ToString("################0.00")
                                Else
                                    CNDN.Target_Qty = dn.Item("data3")
                                    CNDN.Amount = (CDbl(dn.Item("data2")) - CDbl(dr.Item("Amount"))).ToString("################0.00")
                                End If

                                CNDN.Target_Qu = dr.Item("Target_Qu")
                                CNDN.Cond_Type = "ZNET"  'ZNET

                                CNDN_TABLE.Insert(0, CNDN)
                                Exit For
                            End If
                        End If
                    Next
                End If

            Next

            If (CNDN_TABLE.Count > 0) Then
                System.Threading.Thread.Sleep(1000)
                SAP_Data = ClassSAP.SAP_OPEN()
                Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, Iport_Number, Reason, REF_DOC, Remark, Due_Date, EX_Sale, CNDN_TABLE, ZBABI_RET)
                ClassSAP.SAP_CLOSE(SAP_Data)

                Dim clsDB As New ClassDatabase()
                Dim clsFc As New ClassFunction()
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                If (EX_Sale <> "") Then
                    If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                        If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), Iport_Number, REF_DOC, Doc_TYPE, Reason, Due_Date, EX_Sale, Sold_To, "N", Old_Iport_no, conn, tran) > 0) Then
                            For Each dx As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                                If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(Iport_Number, dx.Material, dx.Plant, dx.Target_Qty, dx.Target_Qu, dx.Cond_Type, dx.Amount, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                        Else
                            condition = False
                        End If
                    End If
                End If
                For Each dv As SAP_IPORT.BAPIRET1 In ZBABI_RET
                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Cn_Dn_Request", dv.Type, dv.Id, dv.Number, dv.Message, dv.Log_No, dv.Log_Msg_No, dv.Message_V1, dv.Message_V2, dv.Message_V3, dv.Message_V4, conn, tran) < 1) Then
                        condition = False
                    End If
                Next
                If (condition) Then
                    clsDB.CommitTran(tran)
                Else
                    clsDB.RollBackTran(tran)
                    CheckCompleteAll = False
                End If
                Application.UnLock()
                conn.Dispose()

            End If

            '*******************************************
            'ทำการสร้าง Invoice ใหม่
            dtCNDN = clsGet.GetOrderFor_CreateNewInvoice(ViewState("EditBooking"), ViewState("SoldTo"))
            If (dtCNDN.Rows.Count > 0) Then
                Dim Bill_Date As String = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))
                Dim Berth_UnBerth As String = ""
                Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
                Dim dtLog_Out As DataTable = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
                If (dtActual.Rows.Count > 0) And (dtLog_Out.Rows.Count > 0) Then
                    Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
                    Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
                    Berth_UnBerth = Berthing_Date & " - " & Depart_Actual_Date
                End If
                For Each dr As DataRow In dtCNDN.Rows
                    'Agent
                    If (condition11) Then
                        Dim SoldTo As String = ViewState("SoldTo")
                        Dim Bill_to As String = clsGet.Get_Bill_TO_Bulk(ViewState("EditBooking"), ViewState("SoldTo"))
                        If (Bill_to = "0") Then
                            Bill_to = ViewState("BillTo")
                        ElseIf (Bill_to = "") Then
                            Bill_to = SoldTo
                        End If
                        Dim BABIONETIME As New SAP_IPORT.ZBAPI_SALES_ONETIME
                        Dim BABITable As New SAP_IPORT.BAPIRET1Table

                        Dim BABIHEADER11 As New SAP_IPORT.ZBAPI_SALES_HEADER
                        BABIHEADER11.Doc_Type = "ZSRR"
                        BABIHEADER11.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
                        BABIHEADER11.Sold_To = SoldTo
                        BABIHEADER11.Bill_To = Bill_to
                        BABIHEADER11.Ship_Name = dr.Item("Vehicle_Text")
                        BABIHEADER11.Division = "11"
                        BABIHEADER11.Berth = Berth_UnBerth

                        If (SALE_TABLE11_0.Count > 0) Then
                            Dim EX_BILL_NO As String = ""
                            Dim EX_SALES_NO As String = ""


                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "", Iport_Number, BABIONETIME, BABIHEADER11, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE11_0)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            Dim chkcredit As String = True
                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable
                                    If (dh.Type = "E") Or (dh.Id = "VF") Or (dh.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dh.Type, dh.Id, dh.Number, dh.Message, dh.Log_No, dh.Log_Msg_No, dh.Message_V1, dh.Message_V2, dh.Message_V3, dh.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim ChkCredit_limit As String = ""
                                    If (chkcredit) Then
                                        ChkCredit_limit = "Y"
                                    Else
                                        ChkCredit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(ViewState("EditBooking"), Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO, EX_BILL_NO, Credit_Limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dd As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_0
                                            If (dd.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dd.Material, dd.Plant, dd.Target_Qty, dd.Target_Qu, dd.Cond_Type, dd.Discount, dd.Amount, dd.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If
                            If (condition) Then
                                clsDB.CommitTran(tran)
                                Credit_Limit = chkcredit
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()
                        End If
                        If (SALE_TABLE11_1.Count > 0) Then
                            Dim EX_BILL_NO As String = ""
                            Dim EX_SALES_NO As String = ""


                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "", Iport_Number, BABIONETIME, BABIHEADER11, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE11_1)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            Dim chkcredit As String = True
                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable
                                    If (dh.Type = "E") Or (dh.Id = "VF") Or (dh.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dh.Type, dh.Id, dh.Number, dh.Message, dh.Log_No, dh.Log_Msg_No, dh.Message_V1, dh.Message_V2, dh.Message_V3, dh.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim ChkCredit_limit As String = ""
                                    If (chkcredit) Then
                                        ChkCredit_limit = "Y"
                                    Else
                                        ChkCredit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(ViewState("EditBooking"), Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO, EX_BILL_NO, Credit_Limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dd As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_1
                                            If (dd.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dd.Material, dd.Plant, dd.Target_Qty, dd.Target_Qu, dd.Cond_Type, dd.Discount, dd.Amount, dd.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If
                            If (condition) Then
                                clsDB.CommitTran(tran)
                                Credit_Limit = chkcredit
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()
                        End If
                        If (SALE_TABLE11_5.Count > 0) Then
                            Dim EX_BILL_NO As String = ""
                            Dim EX_SALES_NO As String = ""


                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "", Iport_Number, BABIONETIME, BABIHEADER11, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE11_5)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            Dim chkcredit As String = True
                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable
                                    If (dh.Type = "E") Or (dh.Id = "VF") Or (dh.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dh.Type, dh.Id, dh.Number, dh.Message, dh.Log_No, dh.Log_Msg_No, dh.Message_V1, dh.Message_V2, dh.Message_V3, dh.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim ChkCredit_limit As String = ""
                                    If (chkcredit) Then
                                        ChkCredit_limit = "Y"
                                    Else
                                        ChkCredit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(ViewState("EditBooking"), Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO, EX_BILL_NO, Credit_Limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dd As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_5
                                            If (dd.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dd.Material, dd.Plant, dd.Target_Qty, dd.Target_Qu, dd.Cond_Type, dd.Discount, dd.Amount, dd.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If
                            If (condition) Then
                                clsDB.CommitTran(tran)
                                Credit_Limit = chkcredit
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()
                        End If
                    End If
                    If (condition12) Then
                        Dim SoldTo As String = ViewState("SoldTo")
                        Dim Bill_to As String = clsGet.Get_Bill_TO_Bulk(ViewState("EditBooking"), ViewState("SoldTo"))
                        If (Bill_to = "0") Then
                            Bill_to = ViewState("BillTo")
                        ElseIf (Bill_to = "") Then
                            Bill_to = SoldTo
                        End If
                        Dim BABIONETIME As New SAP_IPORT.ZBAPI_SALES_ONETIME
                        Dim BABITable As New SAP_IPORT.BAPIRET1Table

                        Dim BABIHEADER12 As New SAP_IPORT.ZBAPI_SALES_HEADER
                        BABIHEADER12.Doc_Type = "ZSRR"
                        BABIHEADER12.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
                        BABIHEADER12.Sold_To = SoldTo
                        BABIHEADER12.Bill_To = Bill_to
                        BABIHEADER12.Ship_Name = dr.Item("Vehicle_Text")
                        BABIHEADER12.Division = "12"
                        BABIHEADER12.Berth = Berth_UnBerth

                        If (SALE_TABLE12_0.Count > 0) Then
                            Dim EX_BILL_NO As String = ""
                            Dim EX_SALES_NO As String = ""

                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "", Iport_Number, BABIONETIME, BABIHEADER12, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE12_0)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            Dim chkcredit As String = True
                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable
                                    If (dh.Type = "E") Or (dh.Id = "VF") Or (dh.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dh.Type, dh.Id, dh.Number, dh.Message, dh.Log_No, dh.Log_Msg_No, dh.Message_V1, dh.Message_V2, dh.Message_V3, dh.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim ChkCredit_limit As String = ""
                                    If (chkcredit) Then
                                        ChkCredit_limit = "Y"
                                    Else
                                        ChkCredit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(ViewState("EditBooking"), Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO, EX_BILL_NO, Credit_Limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dd As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_0
                                            If (dd.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dd.Material, dd.Plant, dd.Target_Qty, dd.Target_Qu, dd.Cond_Type, dd.Discount, dd.Amount, dd.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If
                            If (condition) Then
                                clsDB.CommitTran(tran)
                                Credit_Limit = chkcredit
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()
                        End If
                        If (SALE_TABLE12_1.Count > 0) Then
                            Dim EX_BILL_NO As String = ""
                            Dim EX_SALES_NO As String = ""

                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "", Iport_Number, BABIONETIME, BABIHEADER12, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE12_1)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            Dim chkcredit As String = True
                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable
                                    If (dh.Type = "E") Or (dh.Id = "VF") Or (dh.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dh.Type, dh.Id, dh.Number, dh.Message, dh.Log_No, dh.Log_Msg_No, dh.Message_V1, dh.Message_V2, dh.Message_V3, dh.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim ChkCredit_limit As String = ""
                                    If (chkcredit) Then
                                        ChkCredit_limit = "Y"
                                    Else
                                        ChkCredit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(ViewState("EditBooking"), Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO, EX_BILL_NO, Credit_Limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dd As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_1
                                            If (dd.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dd.Material, dd.Plant, dd.Target_Qty, dd.Target_Qu, dd.Cond_Type, dd.Discount, dd.Amount, dd.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If
                            If (condition) Then
                                clsDB.CommitTran(tran)
                                Credit_Limit = chkcredit
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()
                        End If
                        If (SALE_TABLE12_5.Count > 0) Then
                            Dim EX_BILL_NO As String = ""
                            Dim EX_SALES_NO As String = ""

                            SAP_Data = ClassSAP.SAP_OPEN()
                            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                            SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "", Iport_Number, BABIONETIME, BABIHEADER12, EX_BILL_NO, EX_SALES_NO, BABITable, SALE_TABLE12_5)
                            ClassSAP.SAP_CLOSE(SAP_Data)

                            Dim clsDB As New ClassDatabase()
                            Dim clsFc As New ClassFunction()
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Application.Lock()
                            conn.Open()
                            tran = clsDB.BeginTran(conn)
                            Dim chkcredit As String = True
                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable
                                    If (dh.Type = "E") Or (dh.Id = "VF") Or (dh.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dh.Type, dh.Id, dh.Number, dh.Message, dh.Log_No, dh.Log_Msg_No, dh.Message_V1, dh.Message_V2, dh.Message_V3, dh.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim ChkCredit_limit As String = ""
                                    If (chkcredit) Then
                                        ChkCredit_limit = "Y"
                                    Else
                                        ChkCredit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(ViewState("EditBooking"), Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO, EX_BILL_NO, Credit_Limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dd As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_5
                                            If (dd.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dd.Material, dd.Plant, dd.Target_Qty, dd.Target_Qu, dd.Cond_Type, dd.Discount, dd.Amount, dd.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If
                            If (condition) Then
                                clsDB.CommitTran(tran)
                                Credit_Limit = chkcredit
                            Else
                                clsDB.RollBackTran(tran)
                                CheckCompleteAll = False
                            End If
                            Application.UnLock()
                            conn.Dispose()
                        End If
                    End If
                Next

            Else
                'Credit Sale  ทำการ Change Order และทำการออก Billing
                dtMat = ViewState("dtMat")
                'If (ViewState("PORT") = "L") Then
                dtMat = SetMat(dtMat)
                If (Change_Order(dtMat, ViewState("SoldTo"))) Then
                    'ทำการสร้าง Billing
                    Create_Biling()
                End If
                'Else
                '    'Bulk
                '    Dim dsNewBulk As New DataSet
                '    If Not (ViewState("OwnerColumn") & "" = "") Then

                '        Dim Owner() As String = ViewState("OwnerColumn").ToString.Split("$")
                '        Dim Count As Integer = 0
                '        For i As Integer = 0 To Owner.Length - 1
                '            Dim _Owner As String = Owner(i).Split("฿")(0)
                '            If (Owner(i).Split("฿")(1) <> "") Then
                '                'ทำการแยก DataTable ของลูกค้าแต่ละคนออกจากกันเลย
                '                Dim dtN As DataTable = dtMat.Clone
                '                If (dtN.Columns.Count < 17) Then
                '                    dtN.Columns.Add("Owner", GetType(String))
                '                    dtN.AcceptChanges()
                '                End If
                '                For j As Integer = 0 To GridMat.Rows.Count - 1
                '                    Dim chk As CheckBox = CType(GridMat.Rows(j).FindControl("chkOwner" & Count + 1), CheckBox)
                '                    If (chk.Checked) Then
                '                        Dim dr As DataRow = dtN.NewRow
                '                        dr.Item("MATERIAL") = GridMat.DataKeys(j).Values("MATERIAL") & ""
                '                        dr.Item("Text_line") = GridMat.DataKeys(j).Values("Text_line") & ""
                '                        dr.Item("Unit") = GridMat.DataKeys(j).Values("Unit") & ""
                '                        dr.Item("Count") = GridMat.DataKeys(j).Values("Count") & ""
                '                        dr.Item("MAT_Default") = GridMat.DataKeys(j).Values("MAT_Default") & ""
                '                        dr.Item("KBETR") = GridMat.DataKeys(j).Values("KBETR") & ""
                '                        dr.Item("KONWA") = GridMat.DataKeys(j).Values("KONWA") & ""
                '                        dr.Item("MAT_Relation") = GridMat.DataKeys(j).Values("Mat_Relation") & ""
                '                        dr.Item("MAT_Compute") = GridMat.DataKeys(j).Values("MAT_Compute") & ""

                '                        dr.Item("Booking_no") = GridMat.DataKeys(j).Values("Booking_no") & ""
                '                        dr.Item("MAT_Free") = GridMat.DataKeys(j).Values("MAT_Free") & ""
                '                        dr.Item("data1") = GridMat.DataKeys(j).Values("data1") & ""
                '                        dr.Item("data2") = GridMat.DataKeys(j).Values("data2") & ""
                '                        dr.Item("data3") = GridMat.DataKeys(j).Values("data3") & ""
                '                        dr.Item("data4") = GridMat.DataKeys(j).Values("data4") & ""
                '                        dr.Item("New_Old") = GridMat.DataKeys(j).Values("New_Old") & ""

                '                        dr.Item("Owner") = _Owner
                '                        dtN.Rows.Add(dr)
                '                        dtN.AcceptChanges()
                '                    End If
                '                Next
                '                Count += 1
                '                dtN.TableName = "Bulk" & Count
                '                dsNewBulk.Tables.Add(dtN.Copy)
                '            End If
                '        Next
                '    End If
                '    Dim chksale_Order As Boolean = True
                '    For Each dt As DataTable In dsNewBulk.Tables
                '        If dt.Rows.Count > 0 Then
                '            chksale_Order = Change_Order(SetMat(dt), dt.Rows(0).Item("Owner") & "")
                '            If (chksale_Order = False) Then
                '                Exit For
                '            End If
                '        End If
                '    Next
                '    If (chksale_Order) Then
                '        'ทำการสร้าง Billing
                '        Create_Biling()
                '    End If

                'End If

            End If

            If (CheckCompleteAll) Then
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim clsDB As New ClassDatabase
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                If (ViewState("PORT") & "" = "L") Then
                    If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                        condition = False
                    End If
                    clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", conn, tran)
                Else
                    If (dsBooking.Rows(0).Item("MAgent_no") & "" <> ViewState("SoldTo") & "") Then
                        If (clsFc.UpdateBookingProduct_Status(ViewState("EditBooking"), ViewState("SoldTo") & "", "FN", conn, tran) < 1) Then
                            condition = False
                        End If
                    Else
                        If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                            condition = False
                        End If
                    End If
                    clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), ViewState("SoldTo"), conn, tran)
                End If
                If (clsFc.InsertComfirm_Booking(ViewState("EditBooking"), Date.Now.ToString("yyyymmdd"), Date.Now.ToString("HH;mm"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), DateTime.Now.ToString("dd MMM yyyy"), conn, tran) < 1) Then
                    condition = False
                End If

                For Each dr As DataRow In dtMat.Rows
                    If (clsFc.InsertActual_Data_Backup_For_Billing(dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_Compute"), dr.Item("MAT_Free"), dr.Item("data1"), dr.Item("data2"), dr.Item("data3"), dr.Item("data4"), "O", "Y", ViewState("SoldTo"), conn, tran) < 1) Then
                        condition = False
                    End If
                Next

                If (condition) Then
                    clsDB.CommitTran(tran)
                    If (Credit_Limit) Then
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการสร้าง CN/DN และ Invoice เรียบร้อย');", True)
                    Else
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการสร้าง CN/DN และ Invoice เรียบร้อย');", True)
                        ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการสร้าง CN/DN เรียบร้อย , Invoice ติด Credit Limit');", True)
                    End If

                    SendMail(ViewState("EditBooking"), GenBody("รายละเอียดค่าใช้บริการในท่าเรือรายการ Booking No. : " & ViewState("EditBooking")))
                    LoadBOoking()
                Else
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('เกิดความผิดพลาดในการบันทึก');", True)
                End If


            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการสร้าง CN/DN');", True)
            End If
        Else
            'ไม่มีรายการแก้ไข ไม่ต้องทำการสร้าง CNDN
            Dim clsDB As New ClassDatabase()
            Dim clsFc As New ClassFunction()
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim condition As Boolean = True
            Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Application.Lock()
            conn.Open()
            tran = clsDB.BeginTran(conn)

            If (ViewState("PORT") & "" = "L") Then
                If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                    condition = False
                End If
            Else
                If (dsBooking.Rows(0).Item("MAgent_no") & "" <> ViewState("SoldTo") & "") Then
                    If (clsFc.UpdateBookingProduct_Status(ViewState("EditBooking"), ViewState("SoldTo") & "", "FN", conn, tran) < 1) Then
                        condition = False
                    End If
                Else
                    If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "FN", conn, tran) < 1) Then
                        condition = False
                    End If
                End If
            End If
            If (clsFc.InsertComfirm_Booking(ViewState("EditBooking"), Date.Now.ToString("yyyymmdd"), Date.Now.ToString("HH;mm"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), DateTime.Now.ToString("dd MMM yyyy"), conn, tran) < 1) Then
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                SendMail(ViewState("EditBooking"), GenBody("รายละเอียดค่าใช้บริการในท่าเรือรายการ Booking No. : " & ViewState("EditBooking")))
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรียบร้อย ไม่เกิด CN และ DN');", True)
                LoadBOoking()
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
            End If
            Application.UnLock()
            conn.Dispose()
        End If
    End Sub

    Private Function Change_Order(ByVal dtMat As DataTable, ByVal SoldTo As String) As Boolean
        'ต้องทำการหา Sale Order ต้องทำการแยก Mat ตาม Sale ORder ด้วย
        Dim dtSale As DataTable = clsGet.Get_SaleORDER_IPort_Number(ViewState("EditBooking"), SoldTo)
        Dim dtMatOriginal As DataTable = clsGet.GetBookingTariff_Actual(ViewState("EditBooking"), "", "")
        If (ViewState("EditBooking").ToString.Substring(0, 1) = "B") Then
            dtMatOriginal = clsGet.GetActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", False)
        ElseIf (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
            dtMatOriginal = clsGet.GetActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", False)
        End If
        Dim Berth_UnBerth As String = ""
        Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
        Dim dtLog_Out As DataTable = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
        If (dtActual.Rows.Count > 0) And (dtLog_Out.Rows.Count > 0) Then
            Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
            Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
            Berth_UnBerth = Berthing_Date & " - " & Depart_Actual_Date
        End If


        Dim Chkcondition As Boolean = True
        Dim ChkCredit_limit As Boolean = True
        Dim MatNewSale_Order As String = ""
        Dim Plant As String = "1104"
        If (ViewState("PORT") & "" = "L") Then
            Plant = "1103"
        End If
        Dim Owner_Product As String = ""
        If (dtSale.Rows.Count = 0) Then
            For Each dr As DataRow In dtMat.Rows
                If (dr.Item("Material") & "" <> "") Then
                    If (MatNewSale_Order <> "") Then
                        MatNewSale_Order &= "," & dr.Item("Material")
                    Else
                        MatNewSale_Order = dr.Item("Material")
                    End If
                End If
            Next
            'Else
            '    For Each dr As DataRow In dtMat.Rows
            '        Dim chk As Boolean = True
            '        For Each dk As DataRow In dtSale.Rows
            '            Dim dtt As DataTable = clsGet.Get_SaleORDER_Material(dk.Item("Iport_no"))
            '            For Each drtt As DataRow In dtt.Rows
            '                If (dr.Item("Material") = drtt.Item("Material")) Then
            '                    chk = False
            '                    Exit For
            '                End If
            '            Next
            '        Next
            '        If (chk) Then
            '            If (MatNewSale_Order <> "") Then
            '                MatNewSale_Order &= "," & dr.Item("Material")
            '            Else
            '                MatNewSale_Order = dr.Item("Material")
            '            End If
            '        End If
            '    Next
        End If
        If (False) Then
            For Each drsale As DataRow In dtSale.Rows
                Dim IM_SALES_ORDER As String = drsale.Item("EX_SALES_NO")
                Dim IM_IPORTNUMBER As String = drsale.Item("Iport_no")
                Dim dtsale_mat As DataTable = clsGet.Get_SaleORDER_Material(IM_IPORTNUMBER)


                Dim ClassSAP As New Class_SAP
                Dim SAP_Data As Object
                Dim BABITable As New SAP_IPORT.BAPIRET1Table
                Dim Sale_Chg As SAP_IPORT.ZBAPI_SALES_ITEMS_CHG
                Dim Sale_Table As New SAP_IPORT.ZBAPI_SALES_ITEMS_CHGTable

                'กรณีทำการ UPDATE
                Dim MatInsert As String = ""
                Dim MatDelete As String = ""
                Dim MatD As String = ""
                For Each dr As DataRow In dtMatOriginal.Rows
                    ' MatDelete = dr.Item("Material")
                    Dim chkExitLoop As Boolean = False
                    For Each dx As DataRow In dtMat.Rows
                        If (dr.Item("Material") = dx.Item("Material")) Then
                            If (dr.Item("data2") <> dx.Item("data2")) Or (dr.Item("data3") <> dx.Item("data3")) Then
                                ' MatDelete = ""
                                For Each da As DataRow In dtsale_mat.Rows
                                    'ทการตรวจสอบว่าใช่ Mat ของ Sale Order นี้รึป่าว
                                    If (da.Item("Material") = dx.Item("Material")) Then
                                        Dim dtdata As DataTable
                                        If (ViewState("PORT") & "" = "L") Then
                                            dtdata = clsGet.GetOrderFor_CreateCNDN(ViewState("EditBooking"), "'" & dr.Item("Material") & "'", "")
                                        Else
                                            dtdata = clsGet.GetOrderFor_CreateCNDN(ViewState("EditBooking"), "'" & dr.Item("Material") & "'", ViewState("SoldTo"))
                                        End If

                                        Sale_Chg = New SAP_IPORT.ZBAPI_SALES_ITEMS_CHG
                                        Sale_Chg.Updateflag = "U"
                                        Sale_Chg.Material = dr.Item("Material")
                                        Sale_Chg.Target_Qty = dx.Item("data3")
                                        Sale_Chg.Target_Qu = dtdata.Rows(0).Item("Target_Qu")
                                        ' Sale_Chg.Plant = dtdata.Rows(0).Item("Plant")
                                        Sale_Chg.Plant = Plant
                                        Sale_Chg.Cond_Type = "ZB05"
                                        Sale_Chg.Cond_Amount = dx.Item("data2")
                                        Sale_Chg.Disc_Type = ""
                                        Sale_Chg.Disc_Amount = "0"
                                        Sale_Table.Insert(0, Sale_Chg)
                                        chkExitLoop = True
                                        Exit For
                                    End If
                                Next

                            End If
                        End If
                        If (chkExitLoop) Then
                            Exit For
                        End If
                    Next
                    'If (MatDelete <> "") Then
                    '    MatD &= "," & MatDelete
                    'End If
                Next
                'กรณี Insert
                For Each dr As DataRow In dtMat.Rows
                    MatInsert &= "," & dr.Item("Material")
                    For Each dx As DataRow In dtMatOriginal.Rows
                        MatInsert = MatInsert.Replace("," & dx.Item("Material"), "")
                    Next
                Next
                Dim MatI() As String = MatInsert.Split(",")
                If (ViewState("PORT") = "L") Then
                    Plant = "1103"
                Else
                    Plant = "1104"
                End If

                For i As Integer = 0 To MatI.Length - 1
                    If (MatI(i) <> "") Then
                        Dim dtMaterial As DataTable = clsGet.GetMaterialAllByOne(MatI(i))
                        For Each dx As DataRow In dtMat.Rows
                            If (MatI(i) = dx.Item("Material")) Then
                                Dim chk As Boolean = True
                                For Each dv As DataRow In dtsale_mat.Rows
                                    Dim dtMaterialsale As DataTable = clsGet.GetMaterialAllByOne(dv.Item("Material"))
                                    If (dtMaterial.Rows(0).Item("Division") = dtMaterialsale.Rows(0).Item("Division")) And (dtMaterial.Rows(0).Item("TAXCLASS") = dtMaterialsale.Rows(0).Item("TAXCLASS")) Then
                                        chk = False
                                        Dim MAT_FOR As String = clsGet.GetMAT_FOR_FromMaterial(MatI(i))
                                        ' If (MAT_FOR = "A") Then
                                        If (True) Then
                                            'Sold To
                                            ' If (ViewState("SoldTo") = dtsale_mat.Rows(0).Item("Sold_To")) Then
                                            If (True) Then
                                                Sale_Chg = New SAP_IPORT.ZBAPI_SALES_ITEMS_CHG
                                                Sale_Chg.Updateflag = "I"
                                                Sale_Chg.Material = MatI(i)
                                                Sale_Chg.Target_Qty = dx.Item("data3")
                                                Sale_Chg.Target_Qu = clsGet.GetBASE_UOM_FromMaterial(MatI(i))
                                                Sale_Chg.Plant = Plant
                                                Sale_Chg.Cond_Type = "ZB05"
                                                Sale_Chg.Cond_Amount = dx.Item("data2")
                                                Sale_Chg.Disc_Type = ""
                                                Sale_Chg.Disc_Amount = "0"
                                                Sale_Table.Insert(0, Sale_Chg)
                                            End If
                                        Else
                                            'เจ้าของสินค้า
                                            If (ViewState("SoldTo") <> dtsale_mat.Rows(0).Item("Sold_To")) Then
                                                Sale_Chg = New SAP_IPORT.ZBAPI_SALES_ITEMS_CHG
                                                Sale_Chg.Updateflag = "I"
                                                Sale_Chg.Material = MatI(i)
                                                Sale_Chg.Target_Qty = dx.Item("data3")
                                                Sale_Chg.Target_Qu = clsGet.GetBASE_UOM_FromMaterial(MatI(i))
                                                Sale_Chg.Plant = Plant
                                                Sale_Chg.Cond_Type = "ZB05"
                                                Sale_Chg.Cond_Amount = dx.Item("data2")
                                                Sale_Chg.Disc_Type = ""
                                                Sale_Chg.Disc_Amount = "0"
                                                Sale_Table.Insert(0, Sale_Chg)
                                            End If
                                        End If
                                        Exit For
                                    End If
                                Next
                                If (chk) Then
                                    'ไม่พบรายการที่มี Division และ TAXCLASS เดียวกันต้องทำการสร้าง Sale Order ใหม่
                                    MatNewSale_Order &= MatI(i) & ","
                                End If

                            End If
                        Next
                    End If
                Next

                'กรณี Delete
                For Each dr As DataRow In dtMatOriginal.Rows
                    Dim Found As Boolean = True
                    For Each dx As DataRow In dtMat.Rows
                        If (dr.Item("Material") = dx.Item("Material")) Then
                            Found = False
                            Exit For
                        End If
                    Next
                    If (Found) Then
                        MatD &= "," & MatDelete
                    End If
                Next
                Dim Delete() As String = MatD.Split(",")
                For i As Integer = 0 To Delete.Length - 1
                    If (Delete(i) <> "") Then
                        For Each da As DataRow In dtsale_mat.Rows
                            'ทการตรวจสอบว่าใช่ Mat ของ Sale Order นี้รึป่าว
                            If (da.Item("Material") = Delete(i)) Then
                                Sale_Chg = New SAP_IPORT.ZBAPI_SALES_ITEMS_CHG
                                Sale_Chg.Updateflag = "D"
                                Sale_Chg.Material = Delete(i)
                                Sale_Chg.Target_Qty = "0"
                                Sale_Chg.Target_Qu = ""
                                Sale_Chg.Plant = ""
                                Sale_Chg.Cond_Type = "ZB05"
                                Sale_Chg.Cond_Amount = "0"
                                Sale_Chg.Disc_Type = ""
                                Sale_Chg.Disc_Amount = "0"
                                Sale_Table.Insert(0, Sale_Chg)
                                Exit For
                            End If
                        Next

                    End If
                Next
                If (Sale_Table.Count > 0) Then
                    Try
                        Dim Sale_TableTemp As New SAP_IPORT.ZBAPI_SALES_ITEMS_CHGTable
                        Dim BABITableTemp As New SAP_IPORT.BAPIRET1Table
                        'For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS_CHG In Sale_Table
                        '    If (dr.Target_Qu = "D") Then
                        '        dr.Updateflag = "D"

                        '        Sale_Chg = New SAP_IPORT.ZBAPI_SALES_ITEMS_CHG
                        '        Sale_Chg.Updateflag = "I"
                        '        Sale_Chg.Material = dr.Material
                        '        Sale_Chg.Target_Qty = dr.Target_Qty
                        '        Sale_Chg.Target_Qu = dr.Target_Qu
                        '        Sale_Chg.Plant = dr.Plant
                        '        Sale_Chg.Cond_Type = dr.Cond_Type
                        '        Sale_Chg.Cond_Amount = dr.Cond_Amount
                        '        Sale_Chg.Disc_Type = dr.Disc_Type
                        '        Sale_Chg.Disc_Amount = dr.Disc_Amount
                        '        Sale_TableTemp.Insert(0, Sale_Chg)
                        '    End If
                        'Next

                        SAP_Data = ClassSAP.SAP_OPEN()
                        SAP_Data.Zbapi_Iport_Sales_Order_Change(Berth_UnBerth, IM_SALES_ORDER, BABITable, Sale_Table)
                        ClassSAP.SAP_CLOSE(SAP_Data)

                        'If (Sale_TableTemp.Count > 0) Then
                        '    System.Threading.Thread.Sleep(600)
                        '    SAP_Data = ClassSAP.SAP_OPEN()
                        '    SAP_Data.Zbapi_Iport_Sales_Order_Change(Berth_UnBerth, IM_SALES_ORDER, BABITableTemp, Sale_TableTemp)
                        '    ClassSAP.SAP_CLOSE(SAP_Data)
                        'End If


                        Dim clsDB As New ClassDatabase()
                        Dim clsFc As New ClassFunction()
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Application.Lock()
                        conn.Open()
                        tran = clsDB.BeginTran(conn)
                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS_CHG In Sale_Table
                            If (clsFc.InsertSAP_SALE_ORDER_CHANGE(IM_SALES_ORDER, dr.Updateflag, dr.Material, dr.Target_Qty, dr.Target_Qu, dr.Plant, dr.Cond_Type, dr.Cond_Amount, dr.Disc_Type, dr.Disc_Amount, conn, tran) < 1) Then
                                condition = False
                            ElseIf (dr.Updateflag = "U") Then
                                If (clsFc.UpdateSAP_Sale_Order_Material(IM_IPORTNUMBER, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Disc_Amount, (CDbl(dr.Target_Qty) * CDbl(dr.Cond_Amount)).ToString("#############0.00"), conn, tran) < 1) Then
                                    condition = False
                                End If
                            ElseIf (dr.Updateflag = "I") Then
                                clsFc.DeleteSAP_Sale_Order_Material(IM_IPORTNUMBER, dr.Material, conn, tran)
                                If (clsFc.InsertSAP_Sale_Order_Material(IM_IPORTNUMBER, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Disc_Amount, (CDbl(dr.Target_Qty) * CDbl(dr.Cond_Amount)).ToString("#############0.00"), "", conn, tran) < 1) Then
                                    condition = False
                                End If
                            ElseIf (dr.Updateflag = "D") Then
                                If (clsFc.DeleteSAP_Sale_Order_Material(IM_IPORTNUMBER, dr.Material, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If
                        Next
                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS_CHG In Sale_TableTemp
                            If (clsFc.InsertSAP_SALE_ORDER_CHANGE(IM_SALES_ORDER, dr.Updateflag, dr.Material, dr.Target_Qty, dr.Target_Qu, dr.Plant, dr.Cond_Type, dr.Cond_Amount, dr.Disc_Type, dr.Disc_Amount, conn, tran) < 1) Then
                                condition = False
                            ElseIf (dr.Updateflag = "I") Then
                                clsFc.DeleteSAP_Sale_Order_Material(IM_IPORTNUMBER, dr.Material, conn, tran)
                                If (clsFc.InsertSAP_Sale_Order_Material(IM_IPORTNUMBER, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Disc_Amount, (CDbl(dr.Target_Qty) * CDbl(dr.Cond_Amount)).ToString("#############0.00"), "", conn, tran) < 1) Then
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If
                        Next

                        clsFc.DeleteBookingTariff_Actual(ViewState("EditBooking"), conn, tran)
                        For Each dr As DataRow In dtMat.Rows
                            If (clsFc.InsertBookingTariff_Actual2(ViewState("EditBooking"), dr.Item("Material"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR") & "", dr.Item("KONWA") & "", dr.Item("MAT_Relation") & "", dr.Item("MAT_Compute") & "", dr.Item("MAT_Free") & "", dr.Item("data1"), dr.Item("data2"), dr.Item("data3"), (CDbl(dr.Item("data2")) * CDbl(dr.Item("data3"))).ToString("###############0.00"), dr.Item("New_Old"), dr.Item("Owner") & "", conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITable
                            If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                ChkCredit_limit = False
                            End If
                            If (clsFc.InsertSAP_Table_MESSAGE(IM_IPORTNUMBER, "Zbapi_Iport_Sales_Order_Change", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITableTemp
                            If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                ChkCredit_limit = False
                            End If
                            If (clsFc.InsertSAP_Table_MESSAGE(IM_IPORTNUMBER, "Zbapi_Iport_Sales_Order_Change", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (condition) Then
                            clsDB.CommitTran(tran)
                        Else
                            clsDB.RollBackTran(tran)
                            Chkcondition = False
                        End If
                        Application.UnLock()
                        conn.Dispose()
                    Catch ex As Exception
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดปัญหาในการเชื่อมต่อ SAP ');", True)
                        Exit Function
                    End Try
                End If

            Next

        End If
        'ทำการสร้าง Sale_ORder ใหม่
        Dim Mat_Sale_Order() As String = MatNewSale_Order.Split(",")
        If (CreateNewSale_Order(Mat_Sale_Order, SoldTo, ViewState("Vehicle_Text") & "", Plant, dtMat, ViewState("EditBooking"))) Then
            If Not (ChkCredit_limit) Then
                If (Chkcondition) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Document cannot be billed due to credit limit check  ');", True)
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึกข้อมูล ');", True)
                End If
            End If
        Else
            'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการส่งข้อมูลกับ SAP ');", True)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & ViewState("MessageSAP") & "');", True)
            Chkcondition = False
        End If

        Return Chkcondition
    End Function

    Private Function CreateNewSale_Order(ByVal dtMaterial() As String, ByVal Sold_To As String, ByVal Vehicle_Text As String, ByVal Plant As String, ByVal dtMat As DataTable, ByVal Booking_no As String) As Boolean
        Dim Iport_Number As String = clsGet.Get_IportNumber()
        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) - 1).ToString("000")
        Dim Bill_Date As String = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        Dim clsDB As New ClassDatabase()
        Dim chkcredit As String = True   'Check True = ผ่าน , Check False = ติดเครติด
        Dim conditionMaster As Boolean = True

        Dim Berth_UnBerth As String = ""
        Dim dtActual As DataTable = clsGet.GetActualTIme(ViewState("EditBooking"))
        Dim dtLog_Out As DataTable = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
        If (dtActual.Rows.Count > 0) And (dtLog_Out.Rows.Count > 0) Then
            Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
            Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
            Berth_UnBerth = Berthing_Date & " - " & Depart_Actual_Date
        End If

        Dim BABIONETIME11 As New SAP_IPORT.ZBAPI_SALES_ONETIME
        If (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
            Dim dtOther As DataTable = clsGet.Get_OtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1))
            If (dtOther.Rows.Count > 0) Then
                If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                    If (dtOther.Rows(0).Item("Customer_name").ToString.Length < 40) Then
                        BABIONETIME11.Name = dtOther.Rows(0).Item("Customer_name")
                    ElseIf (dtOther.Rows(0).Item("Customer_name").ToString.Length < 80) Then
                        BABIONETIME11.Name = dtOther.Rows(0).Item("Customer_name").ToString.Substring(0, 39)
                        BABIONETIME11.Name_2 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(40, dtOther.Rows(0).Item("Customer_name").ToString.Length - 1)
                    Else
                        BABIONETIME11.Name = dtOther.Rows(0).Item("Customer_name").ToString.Substring(0, 39)
                        BABIONETIME11.Name_2 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(40, 79)
                        BABIONETIME11.Name_3 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(80, dtOther.Rows(0).Item("Customer_name").ToString.Length - 1)
                    End If
                    BABIONETIME11.City = dtOther.Rows(0).Item("City")
                    BABIONETIME11.District = dtOther.Rows(0).Item("District")
                    BABIONETIME11.Location = dtOther.Rows(0).Item("Location")
                    BABIONETIME11.Postl_Cod1 = dtOther.Rows(0).Item("Postal_Code")
                    BABIONETIME11.Str_Suppl3 = dtOther.Rows(0).Item("Str_Sup")
                    BABIONETIME11.Street = dtOther.Rows(0).Item("Street")
                End If
            End If


        End If
        Dim EX_SALES_NO11 As String = ""
        Dim EX_BILL_NO11 As String = ""

        Dim BABIONETIME12 As New SAP_IPORT.ZBAPI_SALES_ONETIME
        If (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
            Dim dtOther As DataTable = clsGet.Get_OtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1))
            If (dtOther.Rows.Count > 0) Then
                If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                    If (dtOther.Rows(0).Item("Customer_name").ToString.Length < 40) Then
                        BABIONETIME12.Name = dtOther.Rows(0).Item("Customer_name")
                    ElseIf (dtOther.Rows(0).Item("Customer_name").ToString.Length < 80) Then
                        BABIONETIME12.Name = dtOther.Rows(0).Item("Customer_name").ToString.Substring(0, 39)
                        BABIONETIME12.Name_2 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(40, dtOther.Rows(0).Item("Customer_name").ToString.Length - 1)
                    Else
                        BABIONETIME12.Name = dtOther.Rows(0).Item("Customer_name").ToString.Substring(0, 39)
                        BABIONETIME12.Name_2 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(40, 79)
                        BABIONETIME12.Name_3 = dtOther.Rows(0).Item("Customer_name").ToString.Substring(80, dtOther.Rows(0).Item("Customer_name").ToString.Length - 1)
                    End If
                    BABIONETIME12.City = dtOther.Rows(0).Item("City")
                    BABIONETIME12.District = dtOther.Rows(0).Item("District")
                    BABIONETIME12.Location = dtOther.Rows(0).Item("Location")
                    BABIONETIME12.Postl_Cod1 = dtOther.Rows(0).Item("Postal_Code")
                    BABIONETIME12.Str_Suppl3 = dtOther.Rows(0).Item("Str_Sup")
                    BABIONETIME12.Street = dtOther.Rows(0).Item("Street")
                End If
            End If


        End If

        Dim BABI_SALE11 As New SAP_IPORT.ZBAPI_SALES_ITEMS
        Dim BABI_SALE12 As New SAP_IPORT.ZBAPI_SALES_ITEMS

        Dim SALE_TABLE11_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE11_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE11_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable


        Dim SALE_TABLE12_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE12_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE12_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable

        Dim BABITable11 As New SAP_IPORT.BAPIRET1Table
        Dim BABITable12 As New SAP_IPORT.BAPIRET1Table

        Dim EX_SALES_NO12 As String = ""
        Dim EX_BILL_NO12 As String = ""

        Dim dtSale_OrderAll As DataTable = clsGet.Get_SaleORDER_IPort_Number(Booking_no, Sold_To)
        If (ViewState("EditBooking").ToString.Substring(0, 1) = "B") Or (ViewState("EditBooking").ToString.Substring(0, 1) = "S") Then
            dtSale_OrderAll = clsGet.Get_SaleORDER_IPort_Number("XXXXXX", "zzz")
        End If
        Dim SoldTo As String = Sold_To
        Dim BillTo As String = ""
        Dim Mat_For As String = "A"
        If (dtSale_OrderAll.Rows.Count > 0) Then
            For Each dl As DataRow In dtSale_OrderAll.Rows
                'If (dl.Item("Sold_To") = Sold_To) Then
                '    SoldTo = Sold_To
                '    ' Mat_For = "A"
                'Else
                '    SoldTo = dl.Item("Sold_To")
                '    'Mat_For = "C"
                'End If
                BillTo = dl.Item("Bill_To")

                Dim BABIHEADER11 As New SAP_IPORT.ZBAPI_SALES_HEADER
                BABIHEADER11.Doc_Type = "ZSRR"
                BABIHEADER11.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
                BABIHEADER11.Sold_To = SoldTo
                BABIHEADER11.Bill_To = ViewState("BillTo")
                BABIHEADER11.Ship_Name = Vehicle_Text
                BABIHEADER11.Division = "11"
                BABIHEADER11.Berth = Berth_UnBerth
                Dim dtOther As DataTable = clsGet.Get_OtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1))
                If (dtOther.Rows.Count > 0) Then
                    If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                        BABIHEADER11.Pmnttrms = "D015"
                    End If
                End If



                Dim BABIHEADER12 As New SAP_IPORT.ZBAPI_SALES_HEADER
                BABIHEADER12.Doc_Type = "ZSRR"
                BABIHEADER12.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
                BABIHEADER12.Sold_To = SoldTo
                BABIHEADER12.Bill_To = ViewState("BillTo")
                BABIHEADER12.Ship_Name = Vehicle_Text
                BABIHEADER12.Division = "12"
                BABIHEADER12.Berth = Berth_UnBerth
                If (dtOther.Rows.Count > 0) Then
                    If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                        BABIHEADER12.Pmnttrms = "D015"
                    End If
                End If

                Dim condition11 As Boolean = False
                Dim condition12 As Boolean = False
                For i As Integer = 0 To dtMaterial.Length - 1
                    If (dtMaterial(i) & "" <> "") Then
                        If (Mat_For = clsGet.GetMAT_FOR_FromMaterial(dtMaterial(i))) Then
                            Dim dtDivisionTAXCLASS As DataTable = clsGet.GetMaterialAllByOne(dtMaterial(i))
                            Dim Target_QU As String = clsGet.GetBASE_UOM_FromMaterial(dtMaterial(i))
                            Dim Target_Qty As String = ""
                            Dim Amount As String = ""
                            Dim LowRate As Double = "0"
                            Dim chkROw As Boolean = False
                            For Each dq As DataRow In dtMat.Rows
                                If (dq.Item("Material") = dtMaterial(i)) Then
                                    Target_Qty = dq.Item("data3")
                                    Amount = dq.Item("data2")
                                    Try

                                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dtMaterial(i))

                                        For Each dw As DataRow In dtLowRate.Rows
                                            If (CDbl(dq.Item("data4")) = CDbl(dl.Item("LowRate"))) Then
                                                LowRate = dq.Item("data4")
                                                chkROw = True
                                                Exit For
                                            End If
                                        Next
                                    Catch ex As Exception
                                        LowRate = "0"
                                        chkROw = False
                                    End Try

                                End If
                            Next
                            If (dtDivisionTAXCLASS.Rows(0).Item("Division") & "" = "11") Then
                                BABI_SALE11 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                                BABI_SALE11.Material = dtMaterial(i)
                                BABI_SALE11.Plant = Plant
                                BABI_SALE11.Target_Qty = Target_Qty
                                BABI_SALE11.Target_Qu = Target_QU
                                BABI_SALE11.Cond_Type = ""
                                BABI_SALE11.Discount = "0"
                                Try
                                    If (chkROw) Then
                                        BABI_SALE11.Amount = LowRate
                                        BABI_SALE11.Condvalue = LowRate
                                    Else
                                        BABI_SALE11.Amount = Amount
                                        BABI_SALE11.Condvalue = "0"
                                    End If
                                Catch ex As Exception
                                    BABI_SALE11.Amount = Amount
                                    BABI_SALE11.Condvalue = "0"
                                End Try
                                If (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "0") Then
                                    SALE_TABLE11_0.Insert(0, BABI_SALE11)
                                ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "1") Then
                                    SALE_TABLE11_1.Insert(0, BABI_SALE11)
                                ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "5") Then
                                    SALE_TABLE11_5.Insert(0, BABI_SALE11)
                                End If
                                condition11 = True
                            ElseIf (dtDivisionTAXCLASS.Rows(0).Item("Division") & "" = "12") Then
                                BABI_SALE12 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                                BABI_SALE12.Material = dtMaterial(i)
                                BABI_SALE12.Plant = Plant
                                BABI_SALE12.Target_Qty = Target_Qty
                                BABI_SALE12.Target_Qu = Target_QU
                                BABI_SALE12.Cond_Type = ""
                                BABI_SALE12.Discount = "0"
                                Try
                                    If (chkROw) Then
                                        BABI_SALE12.Amount = LowRate
                                        BABI_SALE12.Condvalue = LowRate
                                    Else
                                        BABI_SALE12.Amount = Amount
                                        BABI_SALE12.Condvalue = "0"
                                    End If
                                Catch ex As Exception
                                    BABI_SALE12.Amount = Amount
                                    BABI_SALE12.Condvalue = "0"
                                End Try

                                If (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "0") Then
                                    SALE_TABLE12_0.Insert(0, BABI_SALE12)
                                ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "1") Then
                                    SALE_TABLE12_1.Insert(0, BABI_SALE12)
                                ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "5") Then
                                    SALE_TABLE12_5.Insert(0, BABI_SALE12)
                                End If
                                condition12 = True
                            End If
                        End If

                    End If
                Next

                If (condition11) Then
                    If (SALE_TABLE11_0.Count > 0) Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data = ClassSAP.SAP_OPEN()
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", , Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_0)
                        ClassSAP.SAP_CLOSE(SAP_Data)
                        If (EX_SALES_NO11 <> "") Then
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Try
                                conn.Open()
                                tran = clsDB.BeginTran(conn)

                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                            chkcredit = False
                                        End If
                                        If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    Next
                                    If (condition) Then
                                        Dim Credit_limit As String = ""
                                        If (chkcredit) Then
                                            Credit_limit = "Y"
                                        Else
                                            Credit_limit = "N"
                                        End If
                                        If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_0
                                                If (dr.Material <> "") Then
                                                    If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                        condition = False
                                                    End If
                                                End If
                                            Next
                                        Else
                                            condition = False
                                        End If

                                    End If
                                Else
                                    condition = False
                                End If

                                If (condition) Then
                                    clsDB.CommitTran(tran)
                                    InsertActual_Data_Backup_For_Billing()
                                Else
                                    clsDB.RollBackTran(tran)
                                    conditionMaster = False
                                End If
                                If (EX_BILL_NO11 = "") Then
                                    'conditionMaster = False
                                    Dim Message As String = ""
                                    For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                        Message &= dh.Message & " "
                                    Next
                                    ViewState("MessageSAP") = Message
                                End If
                            Catch ex As Exception
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End Try
                            conn.Dispose()
                        Else
                            conditionMaster = False
                            Dim Message As String = ""
                            For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                Message &= dh.Message & " "
                            Next
                            ViewState("MessageSAP") = Message
                        End If
                    End If
                    If (SALE_TABLE11_1.Count > 0) Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data = ClassSAP.SAP_OPEN()
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_1)
                        ClassSAP.SAP_CLOSE(SAP_Data)

                        If (EX_SALES_NO11 <> "") Then
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Try
                                conn.Open()
                                tran = clsDB.BeginTran(conn)

                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                            chkcredit = False
                                        End If
                                        If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    Next
                                    If (condition) Then
                                        Dim Credit_limit As String = ""
                                        If (chkcredit) Then
                                            Credit_limit = "Y"
                                        Else
                                            Credit_limit = "N"
                                        End If
                                        If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_1
                                                If (dr.Material <> "") Then
                                                    If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                        condition = False
                                                    End If
                                                End If
                                            Next
                                        Else
                                            condition = False
                                        End If

                                    End If
                                Else
                                    condition = False
                                End If

                                If (condition) Then
                                    clsDB.CommitTran(tran)
                                    InsertActual_Data_Backup_For_Billing()
                                Else
                                    clsDB.RollBackTran(tran)
                                    conditionMaster = False
                                End If
                                If (EX_BILL_NO11 = "") Then
                                    ' conditionMaster = False
                                    Dim Message As String = ""
                                    For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                        Message &= dh.Message & " "
                                    Next
                                    ViewState("MessageSAP") = Message
                                End If
                            Catch ex As Exception
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End Try
                            conn.Dispose()
                        Else
                            conditionMaster = False
                            Dim Message As String = ""
                            For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                Message &= dh.Message & " "
                            Next
                            ViewState("MessageSAP") = Message
                        End If

                    End If
                    If (SALE_TABLE11_5.Count > 0) Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data = ClassSAP.SAP_OPEN()
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_5)
                        ClassSAP.SAP_CLOSE(SAP_Data)
                        If (EX_SALES_NO11 <> "") Then
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Try
                                conn.Open()
                                tran = clsDB.BeginTran(conn)

                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                            chkcredit = False
                                        End If
                                        If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    Next
                                    If (condition) Then
                                        Dim Credit_limit As String = ""
                                        If (chkcredit) Then
                                            Credit_limit = "Y"
                                        Else
                                            Credit_limit = "N"
                                        End If
                                        If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_5
                                                If (dr.Material <> "") Then
                                                    If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                        condition = False
                                                    End If
                                                End If
                                            Next
                                        Else
                                            condition = False
                                        End If

                                    End If
                                Else
                                    condition = False
                                End If

                                If (condition) Then
                                    clsDB.CommitTran(tran)
                                    InsertActual_Data_Backup_For_Billing()
                                Else
                                    clsDB.RollBackTran(tran)
                                    conditionMaster = False
                                End If
                                If (EX_BILL_NO11 = "") Then
                                    ' conditionMaster = False
                                    Dim Message As String = ""
                                    For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                        Message &= dh.Message & " "
                                    Next
                                    ViewState("MessageSAP") = Message
                                End If
                            Catch ex As Exception
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End Try
                            conn.Dispose()
                        Else
                            conditionMaster = False
                            Dim Message As String = ""
                            For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                Message &= dh.Message & " "
                            Next
                            ViewState("MessageSAP") = Message
                        End If

                    End If
                End If
                If (condition12) Then
                    If SALE_TABLE12_0.Count > 0 Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data = ClassSAP.SAP_OPEN()
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_0)
                        ClassSAP.SAP_CLOSE(SAP_Data)
                        If (EX_SALES_NO12 <> "") Then
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Try
                                conn.Open()
                                tran = clsDB.BeginTran(conn)

                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                            chkcredit = False
                                        End If
                                        If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    Next

                                    If (condition) Then
                                        Dim Credit_limit As String = ""
                                        If (chkcredit) Then
                                            Credit_limit = "Y"
                                        Else
                                            Credit_limit = "N"
                                        End If
                                        If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_0
                                                If (dr.Material <> "") Then
                                                    If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                        condition = False
                                                    End If
                                                End If
                                            Next
                                        Else
                                            condition = False
                                        End If
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If

                                If (condition) Then
                                    clsDB.CommitTran(tran)
                                    InsertActual_Data_Backup_For_Billing()
                                Else
                                    clsDB.RollBackTran(tran)
                                    conditionMaster = False
                                End If
                                If (EX_BILL_NO12 = "") Then
                                    ' conditionMaster = False
                                    Dim Message As String = ""
                                    For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                        Message &= dh.Message & " "
                                    Next
                                    ViewState("MessageSAP") = Message
                                End If
                            Catch ex As Exception
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End Try
                            conn.Dispose()
                        Else
                            conditionMaster = False
                            Dim Message As String = ""
                            For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                Message &= dh.Message & " "
                            Next
                            ViewState("MessageSAP") = Message
                        End If

                    End If
                    If SALE_TABLE12_1.Count > 0 Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data = ClassSAP.SAP_OPEN()
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_1)
                        ClassSAP.SAP_CLOSE(SAP_Data)
                        If (EX_SALES_NO12 <> "") Then
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Try
                                conn.Open()
                                tran = clsDB.BeginTran(conn)

                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                            chkcredit = False
                                        End If
                                        If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    Next

                                    If (condition) Then
                                        Dim Credit_limit As String = ""
                                        If (chkcredit) Then
                                            Credit_limit = "Y"
                                        Else
                                            Credit_limit = "N"
                                        End If
                                        If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_1
                                                If (dr.Material <> "") Then
                                                    If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                        condition = False
                                                    End If
                                                End If
                                            Next
                                        Else
                                            condition = False
                                        End If
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If

                                If (condition) Then
                                    clsDB.CommitTran(tran)
                                    InsertActual_Data_Backup_For_Billing()
                                Else
                                    clsDB.RollBackTran(tran)
                                    conditionMaster = False
                                End If
                                If (EX_BILL_NO12 = "") Then
                                    ' conditionMaster = False
                                    Dim Message As String = ""
                                    For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                        Message &= dh.Message & " "
                                    Next
                                    ViewState("MessageSAP") = Message
                                End If
                            Catch ex As Exception
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End Try
                            conn.Dispose()
                        Else
                            conditionMaster = False
                            Dim Message As String = ""
                            For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                Message &= dh.Message & " "
                            Next
                            ViewState("MessageSAP") = Message
                        End If

                    End If
                    If SALE_TABLE12_5.Count > 0 Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data = ClassSAP.SAP_OPEN()
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_5)
                        ClassSAP.SAP_CLOSE(SAP_Data)
                        If (EX_SALES_NO12 <> "") Then
                            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                            Dim condition As Boolean = True
                            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                            Try
                                conn.Open()
                                tran = clsDB.BeginTran(conn)

                                If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                            chkcredit = False
                                        End If
                                        If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    Next

                                    If (condition) Then
                                        Dim Credit_limit As String = ""
                                        If (chkcredit) Then
                                            Credit_limit = "Y"
                                        Else
                                            Credit_limit = "N"
                                        End If
                                        If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_5
                                                If (dr.Material <> "") Then
                                                    If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                        condition = False
                                                    End If
                                                End If
                                            Next
                                        Else
                                            condition = False
                                        End If
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If

                                If (condition) Then
                                    clsDB.CommitTran(tran)
                                    InsertActual_Data_Backup_For_Billing()
                                Else
                                    clsDB.RollBackTran(tran)
                                    conditionMaster = False
                                End If
                                If (EX_BILL_NO12 = "") Then
                                    ' conditionMaster = False
                                    Dim Message As String = ""
                                    For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                        Message &= dh.Message & " "
                                    Next
                                    ViewState("MessageSAP") = Message
                                End If
                            Catch ex As Exception
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End Try
                            conn.Dispose()
                        Else
                            conditionMaster = False
                            Dim Message As String = ""
                            For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                Message &= dh.Message & " "
                            Next
                            ViewState("MessageSAP") = Message
                        End If

                    End If
                End If
            Next
        Else
            'If (dl.Item("Sold_To") = Sold_To) Then
            '    SoldTo = Sold_To
            '    Mat_For = "A"
            'Else
            '    SoldTo = dl.Item("Sold_To")
            '    Mat_For = "C"
            'End If
            'BillTo = dl.Item("Bill_To")

            Dim BABIHEADER11 As New SAP_IPORT.ZBAPI_SALES_HEADER
            BABIHEADER11.Doc_Type = "ZSRR"
            BABIHEADER11.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
            BABIHEADER11.Sold_To = Sold_To
            BABIHEADER11.Bill_To = ViewState("BillTo")
            BABIHEADER11.Ship_Name = Vehicle_Text
            BABIHEADER11.Division = "11"
            BABIHEADER11.Berth = Berth_UnBerth
            Dim dtOther As DataTable = clsGet.Get_OtherService(ViewState("EditBooking").ToString.Substring(1, ViewState("EditBooking").ToString.Length - 1))
            If (dtOther.Rows.Count > 0) Then
                If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                    BABIHEADER11.Pmnttrms = "D015"
                End If
            End If



            Dim BABIHEADER12 As New SAP_IPORT.ZBAPI_SALES_HEADER
            BABIHEADER12.Doc_Type = "ZSRR"
            BABIHEADER12.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
            BABIHEADER12.Sold_To = Sold_To
            BABIHEADER12.Bill_To = ViewState("BillTo")
            BABIHEADER12.Ship_Name = Vehicle_Text
            BABIHEADER12.Division = "12"
            BABIHEADER12.Berth = Berth_UnBerth

            If (dtOther.Rows.Count > 0) Then
                If (dtOther.Rows(0).Item("Type_Customer") & "" = "O") Then
                    BABIHEADER12.Pmnttrms = "D015"
                End If
            End If


            Dim condition11 As Boolean = False
            Dim condition12 As Boolean = False
            For i As Integer = 0 To dtMaterial.Length - 1
                If (dtMaterial(i) & "" <> "") Then
                    '  If (Mat_For = clsGet.GetMAT_FOR_FromMaterial(dtMaterial(i))) Then
                    If (True) Then
                        Dim dtDivisionTAXCLASS As DataTable = clsGet.GetMaterialAllByOne(dtMaterial(i))
                        Dim Target_QU As String = clsGet.GetBASE_UOM_FromMaterial(dtMaterial(i))
                        Dim Target_Qty As String = ""
                        Dim Amount As String = ""
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dq As DataRow In dtMat.Rows
                            If (dq.Item("Material") = dtMaterial(i)) Then
                                Target_Qty = dq.Item("data3")
                                Amount = dq.Item("data2")
                                Try

                                    Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dtMaterial(i))

                                    For Each dw As DataRow In dtLowRate.Rows
                                        If (CDbl(dq.Item("data4")) = CDbl(dw.Item("LowRate"))) Then
                                            LowRate = dw.Item("LowRate")
                                            chkROw = True
                                            Exit For
                                        End If
                                    Next
                                Catch ex As Exception
                                    LowRate = "0"
                                    chkROw = False
                                End Try
                            End If
                        Next
                        If (dtDivisionTAXCLASS.Rows(0).Item("Division") & "" = "11") Then
                            BABI_SALE11 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                            BABI_SALE11.Material = dtMaterial(i)
                            BABI_SALE11.Plant = Plant
                            BABI_SALE11.Target_Qty = Target_Qty
                            BABI_SALE11.Target_Qu = Target_QU
                            BABI_SALE11.Cond_Type = ""
                            BABI_SALE11.Discount = "0"
                            Try
                                If (chkROw) Then
                                    BABI_SALE11.Amount = LowRate
                                    BABI_SALE11.Condvalue = LowRate
                                Else
                                    BABI_SALE11.Amount = Amount
                                    BABI_SALE11.Condvalue = "0"
                                End If
                            Catch ex As Exception
                                BABI_SALE11.Amount = Amount
                                BABI_SALE11.Condvalue = "0"
                            End Try
                            If (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "0") Then
                                SALE_TABLE11_0.Insert(0, BABI_SALE11)
                            ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "1") Then
                                SALE_TABLE11_1.Insert(0, BABI_SALE11)
                            ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "5") Then
                                SALE_TABLE11_5.Insert(0, BABI_SALE11)
                            End If
                            condition11 = True
                        ElseIf (dtDivisionTAXCLASS.Rows(0).Item("Division") & "" = "12") Then
                            BABI_SALE12 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                            BABI_SALE12.Material = dtMaterial(i)
                            BABI_SALE12.Plant = Plant
                            BABI_SALE12.Target_Qty = Target_Qty
                            BABI_SALE12.Target_Qu = Target_QU
                            BABI_SALE12.Cond_Type = ""
                            BABI_SALE12.Discount = "0"
                            Try
                                If (chkROw) Then
                                    BABI_SALE12.Amount = LowRate
                                    BABI_SALE12.Condvalue = LowRate
                                Else
                                    BABI_SALE12.Amount = Amount
                                    BABI_SALE12.Condvalue = "0"
                                End If
                            Catch ex As Exception
                                BABI_SALE12.Amount = Amount
                                BABI_SALE12.Condvalue = "0"
                            End Try

                            If (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "0") Then
                                SALE_TABLE12_0.Insert(0, BABI_SALE12)
                            ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "1") Then
                                SALE_TABLE12_1.Insert(0, BABI_SALE12)
                            ElseIf (dtDivisionTAXCLASS.Rows(0).Item("TAXCLASS") & "" = "5") Then
                                SALE_TABLE12_5.Insert(0, BABI_SALE12)
                            End If
                            condition12 = True
                        End If
                    End If

                End If
            Next
            If (condition11) Then
                If (SALE_TABLE11_0.Count > 0) Then
                    Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                    SAP_Data = ClassSAP.SAP_OPEN()
                    SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_0)
                    ClassSAP.SAP_CLOSE(SAP_Data)
                    If (EX_SALES_NO11 <> "") Then
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_0
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                                InsertActual_Data_Backup_For_Billing()
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If
                            If (EX_BILL_NO11 = "") Then
                                '  conditionMaster = False
                                Dim Message As String = ""
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                    Message &= dh.Message & " "
                                Next
                                ViewState("MessageSAP") = Message
                            End If
                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    Else
                        conditionMaster = False
                        Dim Message As String = ""
                        For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                            Message &= dh.Message & " "
                        Next
                        ViewState("MessageSAP") = Message
                    End If

                End If
                If (SALE_TABLE11_1.Count > 0) Then
                    Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                    SAP_Data = ClassSAP.SAP_OPEN()
                    SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_1)
                    ClassSAP.SAP_CLOSE(SAP_Data)
                    If (EX_SALES_NO11 <> "") Then
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_1
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                                InsertActual_Data_Backup_For_Billing()
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If
                            If (EX_BILL_NO11 = "") Then
                                ' conditionMaster = False
                                Dim Message As String = ""
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                    Message &= dh.Message & " "
                                Next
                                ViewState("MessageSAP") = Message
                            End If
                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    Else
                        conditionMaster = False
                        Dim Message As String = ""
                        For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                            Message &= dh.Message & " "
                        Next
                        ViewState("MessageSAP") = Message
                    End If

                End If
                If (SALE_TABLE11_5.Count > 0) Then
                    Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                    SAP_Data = ClassSAP.SAP_OPEN()
                    SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_5)
                    ClassSAP.SAP_CLOSE(SAP_Data)
                    If (EX_SALES_NO11 <> "") Then
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_5
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                                InsertActual_Data_Backup_For_Billing()
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If
                            If (EX_BILL_NO11 = "") Then
                                ' conditionMaster = False
                                Dim Message As String = ""
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                                    Message &= dh.Message & " "
                                Next
                                ViewState("MessageSAP") = Message
                            End If
                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    Else
                        conditionMaster = False
                        Dim Message As String = ""
                        For Each dh As SAP_IPORT.BAPIRET1 In BABITable11
                            Message &= dh.Message & " "
                        Next
                        ViewState("MessageSAP") = Message
                    End If

                End If
            End If
            If (condition12) Then
                If SALE_TABLE12_0.Count > 0 Then
                    Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                    SAP_Data = ClassSAP.SAP_OPEN()
                    SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_0)
                    ClassSAP.SAP_CLOSE(SAP_Data)
                    If (EX_SALES_NO12 <> "") Then
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next

                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_0
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                                InsertActual_Data_Backup_For_Billing()
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If
                            If (EX_BILL_NO12 = "") Then
                                '  conditionMaster = False
                                Dim Message As String = ""
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                    Message &= dh.Message & " "
                                Next
                                ViewState("MessageSAP") = Message
                            End If
                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    Else
                        conditionMaster = False
                        Dim Message As String = ""
                        For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                            Message &= dh.Message & " "
                        Next
                        ViewState("MessageSAP") = Message
                    End If


                End If
                If SALE_TABLE12_1.Count > 0 Then
                    Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                    SAP_Data = ClassSAP.SAP_OPEN()
                    SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_1)
                    ClassSAP.SAP_CLOSE(SAP_Data)
                    If (EX_SALES_NO12 <> "") Then
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next

                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_1
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                                InsertActual_Data_Backup_For_Billing()
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If
                            If (EX_BILL_NO12 = "") Then
                                ' conditionMaster = False
                                Dim Message As String = ""
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                    Message &= dh.Message & " "
                                Next
                                ViewState("MessageSAP") = Message
                            End If
                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    Else
                        conditionMaster = False
                        Dim Message As String = ""
                        For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                            Message &= dh.Message & " "
                        Next
                        ViewState("MessageSAP") = Message
                    End If

                End If
                If SALE_TABLE12_5.Count > 0 Then
                    Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                    SAP_Data = ClassSAP.SAP_OPEN()
                    SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_5)
                    ClassSAP.SAP_CLOSE(SAP_Data)
                    If (EX_SALES_NO12 <> "") Then
                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next

                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_5
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                                InsertActual_Data_Backup_For_Billing()
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If
                            If (EX_BILL_NO12 = "") Then
                                'conditionMaster = False
                                Dim Message As String = ""
                                For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                                    Message &= dh.Message & " "
                                Next
                                ViewState("MessageSAP") = Message
                            End If
                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    Else
                        conditionMaster = False
                        Dim Message As String = ""
                        For Each dh As SAP_IPORT.BAPIRET1 In BABITable12
                            Message &= dh.Message & " "
                        Next
                        ViewState("MessageSAP") = Message
                    End If

                End If
            End If
        End If

        ClassSAP.SAP_CLOSE(SAP_Data)
        Return conditionMaster
    End Function

    Private Sub GridMat_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridMat.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            If (e.Row.RowIndex = 0) Then
                lbNet.Text = "0"
            End If
            Dim txtData4 As TextBox = CType(e.Row.FindControl("txtData4"), TextBox)

            txtData4.Text = FormatNumber(txtData4.Text, 2)
            If ((GridMat.DataKeys(e.Row.RowIndex).Values("MATERIAL") & "" = "000000002100000236") Or (GridMat.DataKeys(e.Row.RowIndex).Values("MATERIAL") & "" = "000000002100000197")) Then
                txtData4.Enabled = True
            Else
                txtData4.Enabled = False
            End If
            ' If (ViewState("PORT") & "" = "B") Then
            Dim chkbox As String = clsGet.Get_Booking_For_MAT_FREE_REPORT_Item_By_Material_Get_FOR_BULK(GridMat.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", GridMat.DataKeys(e.Row.RowIndex).Values("MATERIAL") & "")
            Dim chk As CheckBox = CType(e.Row.FindControl("chk"), CheckBox)
            If (GridMat.DataKeys(e.Row.RowIndex).Values("Booking_no").ToString.Substring(0, 1) = "S") Or (GridMat.DataKeys(e.Row.RowIndex).Values("Booking_no").ToString.Substring(0, 1) = "S") Then
                chk.Checked = True
            Else
                If (chkbox = "Y") Then
                    chk.Checked = True
                Else
                    chk.Checked = False
                End If
            End If

            ' End If
            'If (ViewState("PORT") & "" = "B") Then
            chk = CType(e.Row.FindControl("chk"), CheckBox)
            If (chk.Checked) Then
                lbNet.Text = FormatNumber(CDbl(lbNet.Text) + CDbl(txtData4.Text), 2)
            End If
            'Else
            '  lbNet.Text = FormatNumber(CDbl(lbNet.Text) + CDbl(txtData4.Text), 2)
            '  End If

        End If
    End Sub

    Private Sub btnBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBack.Click
        LoadBOoking()
    End Sub

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click

        Dim optWindow As String = "left=0,top=0,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no"
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "window.open('" + CreateReport() + "','_blank','" + optWindow + "');", True)
    End Sub

    Private Function CreateReport() As String
        Dim service As New _ReportingService.Report
        Dim Orientation As Boolean = True
        Dim ReportName As String = String.Empty
        Dim reportDataSource As String = String.Empty
        Dim paraName As String = String.Empty
        Dim paraValue As String = String.Empty
        Dim reportType As String = String.Empty
        Dim urlDisplay As String = String.Empty
        Dim dsReport As New DataSet

        Dim Vat As String = ""
        Dim dsConfig As DataSet = Session("Config")
        If (dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(1) = "00") Then
            Vat = CInt(dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(0)).ToString()
        Else
            Vat = dsConfig.Tables(0).Rows(0).Item("Vat").ToString()
        End If


        Dim dt As DataTable
        If (ViewState("PORT") & "" = "B") Then
            dt = clsGet.GetActual_Data_Backup_For_Billing(ViewState("EditBooking"), ViewState("SoldTo"), True)
        Else
            dt = clsGet.GetActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", True)
        End If
        If dt.Rows.Count > 0 Then

            dt.Columns.Add("VAT", GetType(String))
            dt.Columns.Add("VAT_AMOUNT", GetType(String))
            dt.Columns.Add("NET", GetType(String))
            dt.Columns.Add("AMOUNT", GetType(String))
            dt.Columns.Add("Text_AMOUNT", GetType(String))
            dt.AcceptChanges()
            Dim NET As Double = 0.0
            For i As Integer = 0 To dt.Rows.Count - 1
                NET = NET + CDbl(CDbl(dt.Rows(i).Item("data4")).ToString("##############0.00"))
            Next
            Dim VAT_AMOUNT As String = ((NET * CDbl(Vat)) / 100).ToString("############.00")
            Dim AMOUNT As String = NET + CDbl(((NET * CDbl(Vat)) / 100).ToString("############.00"))
            Dim Text_AMOUNT As String = ConvertMoneyToText((NET + CDbl(((NET * CDbl(Vat)) / 100).ToString("############.00"))).ToString())
            For i As Integer = 0 To dt.Rows.Count - 1
                Dim MAT As String = ""
                Try
                    MAT = CInt(dt.Rows(i).Item("MATERIAL"))
                Catch ex As Exception
                    MAT = dt.Rows(i).Item("MATERIAL")
                End Try
                dt.Rows(i).Item("MATERIAL") = MAT
                dt.Rows(i).Item("VAT") = Vat
                dt.Rows(i).Item("VAT_AMOUNT") = FormatNumber(VAT_AMOUNT, 2)
                dt.Rows(i).Item("NET") = FormatNumber(NET, 2)
                dt.Rows(i).Item("AMOUNT") = FormatNumber(AMOUNT, 2)
                dt.Rows(i).Item("Text_AMOUNT") = Text_AMOUNT
                Try
                    dt.Rows(i).Item("data1") = FormatNumber(dt.Rows(i).Item("data1"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data2") = FormatNumber(dt.Rows(i).Item("data2"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data3") = FormatNumber(dt.Rows(i).Item("data3"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data4") = FormatNumber(dt.Rows(i).Item("data4"), 2)
                Catch ex As Exception

                End Try
                dt.AcceptChanges()
            Next
            Dim WHT As Double = 0.0
            For Each dls As DataRow In dt.Rows
                Try
                    Dim dtx As DataTable = clsGet.Get_MeterailWhithodingTax(dls.Item("MATERIAL"))
                    If (dtx.Rows(0).Item("MAT_WHT") & "" = "01") Or (dtx.Rows(0).Item("MAT_WHT") & "" = "02") Or (dtx.Rows(0).Item("MAT_WHT") & "" = "03") Then
                        '1%
                        WHT = (WHT + CDbl(((CDbl(dls.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dtx.Rows(0).Item("MAT_WHT") & "" = "04") Or (dtx.Rows(0).Item("MAT_WHT") & "" = "05") Then
                        '3%
                        WHT = (WHT + CDbl(((CDbl(dls.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dtx.Rows(0).Item("MAT_WHT") & "" = "06") Or (dtx.Rows(0).Item("MAT_WHT") & "" = "22") Then
                        '5%
                        WHT = (WHT + CDbl(((CDbl(dls.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    End If
                Catch ex As Exception

                End Try

            Next
            dsReport.Tables.Add(dt.Copy)


            dsReport.AcceptChanges()
            ReportName = "Actual_Report.rdlc"
            ' dsReport = New DataSet
            reportDataSource = "Actual_Report_Actual"

            dt = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)


            paraName = "SHIP;PERIOD;LAYTIME;AGENT;LOA;GRT;DWT;PO;WHARF;Booking_no;Estimate;Net;Vat;WHT;SUM;Product"
            If (dt.Rows.Count > 0) Then
                Dim SHip As String = dt.Rows(0).Item("Vehicle_Text")
                Dim AGENT As String = dt.Rows(0).Item("MAgent_name")
                Try
                    AGENT = CInt(lbAgent.Text.Split("-")(0)) & "-" & lbAgent.Text.Split("-")(1)
                Catch ex As Exception

                End Try
                Dim LOA As String = dt.Rows(0).Item("Vehicle_LOA")
                Dim GRT As String = dt.Rows(0).Item("Vehicle_GRT")
                Dim DWT As String = dt.Rows(0).Item("Vehicle_DWT")
                Dim PORT As String = dt.Rows(0).Item("PORT")
                ' Dim LAYTIME As String = dt.Rows(0).Item("Lay_Time")
                Dim Berthing_Date As String = ""
                Dim Berthing_TimeTo As String = ""
                Dim POB_Date As String = ""
                Dim POB_Time As String = ""
                Dim Date_From As String = dt.Rows(0).Item("Date_From")
                Dim Date_To As String = dt.Rows(0).Item("Date_To")
                Dim Disconnect_Date As String = ""
                Dim Disconnect_to As String = ""

                dt = clsGet.Get_BookingWharf(ViewState("EditBooking"))
                Dim WHARF As String = dt.Rows(0).Item("Wharf")
                dt = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), "")
                Dim PO As String = "0"
                For Each dr As DataRow In dt.Rows
                    Try
                        Disconnect_Date = dr.Item("LU_Disconnect_Date")
                        Disconnect_to = dr.Item("LU_Disconnect_To")
                        If PORT = "L" Then
                            PO = CDbl(PO) + CDbl(dr.Item("LU_SLMT"))
                        Else
                            PO = CDbl(PO) + CDbl(dr.Item("LU_SUMT"))
                        End If
                    Catch ex As Exception

                    End Try
                Next
                Dim Product As String = ""
                dt = clsGet.Get_Booking_Product(ViewState("EditBooking"))
                For Each dp As DataRow In dt.Rows
                    If Product = "" Then
                        Product = dp.Item("Product_name")
                    Else
                        Product &= "," & dp.Item("Product_name")
                    End If
                Next

                Dim dtGet_Billing_Date As DataTable = clsGet.Get_SaleORDER_IPort_Number(ViewState("EditBooking"), "")
                Dim LAYTIME As String = ""
                If (dtGet_Billing_Date.Rows.Count > 0) Then
                    Dim DateAP As String = dtGet_Billing_Date.Rows(0).Item("Billing_Date") & ""
                    Try
                        DateAP = DateAP.Split(" ")(DateAP.Split(" ").Count - 1)
                        DateAP = DateAP.Split(":")(0)
                        LAYTIME = DateAP.Substring(6, 2) & " " & GetNameMonth(DateAP.Substring(4, 2)) & " " & CInt(DateAP.Substring(0, 4))
                    Catch ex As Exception

                    End Try
                End If
                'If (LAYTIME <> "0") Then
                '    Dim dtLogIn As DataTable = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
                '    Dim dtProduct As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"))
                '    Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(ViewState("EditBooking"))
                '    If (PORT = "L") Then

                '        Dim Product_no As String = ""
                '        Try
                '            Dim sort As Integer = 0
                '            For Each dr As DataRow In dtProduct.Rows
                '                If (CInt(dr.Item("Product_Index") & "") > sort) Then
                '                    sort = CInt(dr.Item("Product_Index"))
                '                    Product_no = dr.Item("Product_no")
                '                End If
                '            Next
                '        Catch ex As Exception

                '        End Try
                '        Dim dtLoad As DataTable = clsGet.Get_Load_Unload_Vessel(ViewState("EditBooking"))
                '        Dim NOR As String = ""
                '        Dim NOR_Time As String = ""
                '        Dim POB As String = ""
                '        POB_Time = ""
                '        If (dtLoad.Rows.Count > 0) Then
                '            If (dtLoad.Rows(0).Item("NOR_Date") & "" <> "") Then
                '                NOR = dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(3, 2)) & " 20" & dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(6, 2)
                '                NOR_Time = dtLoad.Rows(0).Item("NOR_Time") & ""
                '            Else
                '                NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                '                NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                '            End If
                '        Else
                '            NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                '            NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                '        End If
                '        If (dtLogIn.Rows(0).Item("POB_Date") & "" <> "") Then
                '            If (dtLogIn.Rows(0).Item("Up_Date") & "" <> "") Then
                '                If (CDate(dtLogIn.Rows(0).Item("POB_Date")) < CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                '                    POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                '                    POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                '                ElseIf (CDate(dtLogIn.Rows(0).Item("POB_Date")) = CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                '                    If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                '                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                '                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                '                    ElseIf (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) = CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                '                        If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(1)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(1))) Then
                '                            POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                '                            POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                '                        Else
                '                            POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                '                            POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                '                        End If
                '                    Else
                '                        POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                '                        POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                '                    End If
                '                Else
                '                    POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                '                    POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                '                End If
                '            Else
                '                POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                '                POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                '            End If
                '        Else
                '            POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                '            POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                '        End If

                '        dtLoad = clsGet.Get_Load_Unload_Product(ViewState("EditBooking"), Product_no)

                '        Dim Berthing_DateL As String = dtLogIn.Rows(0).Item("Berthing_Date")
                '        Try
                '            Try
                '                If (CInt(dtLogIn.Rows(0).Item("Berthing_TimeTo").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Berthing_TimeFrom").ToString.Split(":")(0))) Then
                '                    Berthing_Date = CDate(Berthing_Date).AddDays(1).ToString("dd MMM", New CultureInfo("en-US")) & " " & Berthing_Date.Split(" ")(2)
                '                End If
                '            Catch ex As Exception

                '            End Try
                '        Catch ex As Exception

                '        End Try
                '        If (dtLoad.Rows.Count > 0) Then
                '            LAYTIME = clsGet.ComputeRemainLaytime(Berthing_DateL, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, dtLoad.Rows(0).Item("LU_Disconnect_Date") & "", dtLoad.Rows(0).Item("LU_Disconnect_To") & "", NOR, NOR_Time)
                '        Else
                '            LAYTIME = clsGet.ComputeRemainLaytime(Berthing_DateL, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, "", "", NOR, NOR_Time)
                '        End If

                '    Else
                '        'Bulk
                '        Dim dtProductBulk As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"))
                '        If (dtProductBulk.Rows.Count > 0) Then
                '            Dim chkCoil As Boolean = False
                '            For Each dx As DataRow In dtProductBulk.Rows
                '                If (dx.Item("Group_no") & "" = "00007") Then
                '                    chkCoil = True
                '                    Exit For
                '                End If
                '            Next
                '            If (chkCoil) Then
                '                Dim LY As Integer = CInt(dsBooking.Tables(0).Rows(0).Item("Lay_Time"))
                '                dtProductBulk = clsGet.Get_Load_Unload_Vessel_Product_Detail(ViewState("EditBooking"))
                '                If (dtProductBulk.Rows.Count > 0) Then
                '                    For Each dr As DataRow In dtProductBulk.Rows
                '                        Dim ts = DateDiff("n", dr.Item("LU_StartActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dr.Item("LU_StartActual_Date").ToString.Substring(3, 2)) & " 20" & dr.Item("LU_StartActual_Date").ToString.Substring(6, 2) & " " & dr.Item("LU_StartActual_Time"), dr.Item("LU_StopActual_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dr.Item("LU_StopActual_Date").ToString.Substring(3, 2)) & " 20" & dr.Item("LU_StopActual_Date").ToString.Substring(6, 2) & " " & dr.Item("LU_StopActual_Time"))
                '                        Dim Hour As String = "0"
                '                        Dim chksub As String = ""
                '                        Dim Minute As String = "0"
                '                        If (LY >= (ts \ 60)) Then
                '                            If (LY = (ts \ 60)) Then
                '                                If (ts Mod 60) > 0 Then
                '                                    chksub = "-"
                '                                    Hour = ((ts \ 60) - LY)
                '                                    Minute = (ts Mod 60)
                '                                Else
                '                                    If (ts Mod 60) > 0 Then
                '                                        Minute = 60 - (ts Mod 60)
                '                                        LY -= 1
                '                                    End If
                '                                    Hour = LY - (ts \ 60)
                '                                End If
                '                            Else
                '                                If (ts Mod 60) > 0 Then
                '                                    Minute = 60 - (ts Mod 60)
                '                                    LY -= 1
                '                                End If
                '                                Hour = LY - (ts \ 60)
                '                            End If
                '                        Else
                '                            chksub = "-"
                '                            Hour = ((ts \ 60) - LY)
                '                            Minute = (ts Mod 60)
                '                        End If
                '                        LAYTIME = chksub & Hour & ":" & CInt(Minute).ToString("00")

                '                    Next
                '                End If
                '            End If
                '        End If
                '    End If
                'End If
                dt = clsGet.Get_Booking_LogSheet_In(ViewState("EditBooking"))
                Dim PERIOD As String = dt.Rows(0).Item("Berthing_Date") & " " & dt.Rows(0).Item("Berthing_TimeFrom")
                Berthing_Date = dt.Rows(0).Item("Berthing_Date")
                Berthing_TimeTo = dt.Rows(0).Item("Berthing_TimeTo")
                POB_Date = dt.Rows(0).Item("POB_Date")
                POB_Time = dt.Rows(0).Item("POB_Time")
                dt = clsGet.Get_Booking_LogSheet_Out(ViewState("EditBooking"))
                PERIOD &= " - " & dt.Rows(0).Item("Last_Date") & " " & dt.Rows(0).Item("Last_Time")


                paraValue = SHip & ";" & PERIOD & ";" & LAYTIME & ";" & AGENT & ";" & FormatNumber(LOA, 2) & ";" & FormatNumber(GRT, 2) & ";" & FormatNumber(DWT, 2) & ";" & FormatNumber(PO, 2) & " MT" & ";" & WHARF & ";" & ViewState("EditBooking") & ";;" & NET & ";" & ((NET * CDbl(Vat)) / 100).ToString("############.00") & ";" & WHT & ";" & ((CDbl(NET) + CDbl((NET * CDbl(Vat)) / 100)) - CDbl(WHT)).ToString("#############0.00") & ";" & Product
            Else
                If ((ViewState("EditBooking").ToString.Substring(0, 1) = "B") Or (ViewState("EditBooking").ToString.Substring(0, 1) = "S")) Then
                    Dim AGENT As String = ""
                    Try
                        AGENT = CInt(lbAgent.Text.Split("-")(0)) & "-" & lbAgent.Text.Split("-")(1)
                    Catch ex As Exception
                        AGENT = lbAgent.Text
                    End Try

                    paraValue = ";;;" & AGENT & ";;;;;;" & ViewState("EditBooking") & ";;" & NET & ";" & ((NET * CDbl(Vat)) / 100).ToString("############.00") & ";" & WHT & ";" & ((CDbl(NET) + CDbl((NET * CDbl(Vat)) / 100)) - CDbl(WHT)).ToString("#############0.00") & ";"
                Else
                    paraValue = ";;;;;;;;;;;0;0;0;0;"
                End If

            End If

            Orientation = True
            reportType = "pdf"

            Try
                urlDisplay = service.CreateReporting(dsReport, reportDataSource, reportType, ReportName, paraName, paraValue, Orientation, "")

                Return urlDisplay
            Catch ex As Exception
                lbNet.Text = ex.Message
            End Try
        Else
            Return ""
        End If
    End Function


    Private Sub btnPrintCNDN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrintCNDN.Click
        Dim service As New _ReportingService.Report

        Dim optWindow As String = "left=0,top=0,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no"
        Dim Orientation As Boolean = True
        Dim ReportName As String = String.Empty
        Dim reportDataSource As String = String.Empty
        Dim paraName As String = String.Empty
        Dim paraValue As String = String.Empty
        Dim reportType As String = String.Empty
        Dim urlDisplay As String = String.Empty
        Dim dsReport As New DataSet

        Dim dt As New DataTable
        dt.Columns.Add("MAgent_name", GetType(String))
        dt.Columns.Add("Biiling_no", GetType(String))
        dt.Columns.Add("Text_line", GetType(String))
        dt.Columns.Add("DN_Qty", GetType(String))
        dt.Columns.Add("DN_Amount", GetType(String))
        dt.Columns.Add("DN_Sum", GetType(String))
        dt.Columns.Add("CN_Qty", GetType(String))
        dt.Columns.Add("CN_Amount", GetType(String))
        dt.Columns.Add("CN_Sum", GetType(String))
        dt.Columns.Add("Sale_Order", GetType(String))
        dt.Columns.Add("Total", GetType(String))
        dt.Columns.Add("Date_Current", GetType(String))
        dt.Columns.Add("Booking_no", GetType(String))
        dt.AcceptChanges()

        Dim dtCNDN As DataTable = clsGet.GetBlock_CNDNByOne(ViewState("EditBooking"), ViewState("SoldTo"))
        Dim dtName As DataTable = clsGet.Get_Customer(ViewState("SoldTo"))
        Dim Name As String
        If (dtName.Rows.Count > 0) Then
            Name = dtName.Rows(0).Item("NAME1") & " " & dtName.Rows(0).Item("NAME2") & " " & dtName.Rows(0).Item("NAME3")
        Else
            Name = dtCNDN.Rows(0).Item("MAgent_Name") & ""
        End If
        If dtCNDN.Rows.Count > 0 Then
            Dim SumDN As String = "0"
            Dim SumCN As String = "0"
            For Each dn As DataRow In dtCNDN.Rows
                Dim dr As DataRow = dt.NewRow()
                dr.Item("MAgent_name") = Name
                dr.Item("Biiling_no") = dn.Item("IM_REF_DOC") & ""
                dr.Item("Booking_no") = ViewState("EditBooking")
                Dim DN_QTY As String = ""
                Dim DN_Price As String = ""
                Dim CN_QTY As String = ""
                Dim CN_Price As String = ""
                If (dn.Item("IM_REASON") & "" = "Z03") Then
                    If (dn.Item("IM_DOCTYPE") = "ZCR") Then
                        CN_QTY = dn.Item("Target_Qty")
                        CN_Price = CDbl(dn.Item("Amount")) * CDbl(CN_QTY)
                        SumCN = (CDbl(SumCN) + CDbl(CN_Price)).ToString("#####################00.00")
                    Else
                        DN_QTY = dn.Item("Target_Qty")
                        DN_Price = CDbl(dn.Item("Amount")) * CDbl(DN_QTY)
                        SumDN = (CDbl(SumDN) + CDbl(DN_Price)).ToString("#####################00.00")
                    End If
                Else
                    If (dn.Item("Target_QU") & "" = "JOB") Then
                        If (dn.Item("IM_DOCTYPE") = "ZCR") Then
                            'Z02
                            ' CN_QTY = dn.Item("Target_Qty")
                            CN_QTY = ""
                            CN_Price = dn.Item("Amount")
                            SumCN = (CDbl(SumCN) + CDbl(CN_Price)).ToString("#####################00.00")
                        Else
                            'Z01 
                            ' DN_QTY = dn.Item("Target_Qty")
                            CN_QTY = ""
                            DN_Price = dn.Item("Amount")
                            SumDN = (CDbl(SumDN) + CDbl(DN_Price)).ToString("#####################00.00")
                        End If
                    Else
                        Dim dw As DataTable = clsGet.GetBookingTariff_Actual(ViewState("EditBooking"), dn.Item("Material"), "")
                        If (dn.Item("IM_DOCTYPE") = "ZCR") Then
                            'Z01ใหม่น้อยกว่า
                            ' CN_QTY = dn.Item("Target_Qty")
                            CN_QTY = ""

                            If (dw.Rows.Count > 0) Then
                                CN_Price = ((CDbl(dn.Item("Amount") + CDbl(dw.Rows(0).Item("data2")))) * CDbl(dn.Item("Target_Qty"))) - (CDbl(dn.Item("Amount")) * CDbl(dn.Item("Target_Qty")))
                            Else
                                CN_Price = (CDbl(dn.Item("Amount")) * CDbl(dn.Item("Target_Qty")))
                            End If

                            SumCN = (CDbl(SumCN) + CDbl(CN_Price)).ToString("#####################00.00")
                        Else
                            'Z02  
                            ' DN_QTY = dn.Item("Target_Qty")
                            CN_QTY = ""
                            If (dw.Rows.Count > 0) Then
                                DN_Price = (CDbl(dn.Item("Amount")) * CDbl(dn.Item("Target_Qty"))) - ((CDbl(dn.Item("Amount") - CDbl(dw.Rows(0).Item("data2")))) * CDbl(dn.Item("Target_Qty")))
                            Else
                                DN_Price = (CDbl(dn.Item("Amount")) * CDbl(dn.Item("Target_Qty")))
                            End If
                            SumDN = (CDbl(SumDN) + CDbl(DN_Price)).ToString("#####################00.00")
                        End If
                    End If

                End If

                dr.Item("Text_line") = dn.Item("Text_line") & ""
                Try
                    dr.Item("DN_Qty") = FormatNumber(DN_QTY, 2)
                Catch ex As Exception
                    dr.Item("DN_Qty") = DN_QTY
                End Try
                Try
                    dr.Item("DN_Amount") = FormatNumber(DN_Price, 2)
                Catch ex As Exception
                    dr.Item("DN_Amount") = DN_Price
                End Try
                Try
                    dr.Item("CN_Qty") = FormatNumber(CN_QTY, 2)
                Catch ex As Exception
                    dr.Item("CN_Qty") = CN_QTY
                End Try
                Try
                    dr.Item("CN_Amount") = FormatNumber(CN_Price, 2)
                Catch ex As Exception
                    dr.Item("CN_Amount") = CN_Price
                End Try



                dr.Item("DN_Sum") = SumDN
                dr.Item("CN_Sum") = SumCN
                dr.Item("Sale_Order") = dn.Item("EX_SALES_NO") & ""
                dr.Item("Total") = (CDbl(SumDN) - CDbl(SumCN)).ToString("#########################0.00")
                dr.Item("Date_Current") = Date.Now.ToString("dd/MM/yyyy", New CultureInfo("en-US"))
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            Next
            For Each dr As DataRow In dt.Rows
                Try
                    dr.Item("DN_SUM") = FormatNumber(SumDN, 2)
                Catch ex As Exception
                    dr.Item("DN_SUM") = SumDN
                End Try
                Try
                    dr.Item("CN_SUM") = FormatNumber(SumCN, 2)
                Catch ex As Exception
                    dr.Item("CN_SUM") = SumCN
                End Try


                dr.Item("Total") = FormatNumber((CDbl(SumDN) - CDbl(SumCN)).ToString("#########################0.00"), 2)
                dt.AcceptChanges()
            Next
            dsReport.Tables.Add(dt)
            dsReport.AcceptChanges()
            ReportName = "CNDN.rdlc"
            ' dsReport = New DataSet
            reportDataSource = "CNDN_CNDN"
            paraName = ""
            paraValue = ""
            Orientation = True
            reportType = "pdf"

            urlDisplay = service.CreateReporting(dsReport, reportDataSource, reportType, ReportName, paraName, paraValue, Orientation, "")

            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "window.open('" + urlDisplay + "','_blank','" + optWindow + "');", True)
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('ไม่พบรายการ CN/DN');", True)
        End If
    End Sub

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        InsertActual_Data_Backup_For_Billing()
        If (txtid.Text.Trim() <> "") Or (txtBillTo.Text.Trim() <> "") Then
            UpdateAgent()
        End If

    End Sub

    Private Sub InsertActual_Data_Backup_For_Billing()
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing

        Dim dtMat As DataTable = ViewState("dtMat")

        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)
        If (ViewState("PORT") & "" = "L") Then
            clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", conn, tran)
        Else
            clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), ViewState("SoldTo"), conn, tran)
        End If

        For Each dr As DataRow In dtMat.Rows
            Dim chkbox As String = "N"
            If Not ((ViewState("EditBooking").ToString.Substring(0, 1) = "B") Or (ViewState("EditBooking").ToString.Substring(0, 1) = "S")) Then
                For i As Integer = 0 To GridMat.Rows.Count - 1
                    If (dr.Item("MATERIAL") = GridMat.DataKeys(i).Values("MATERIAL")) Then
                        Dim chk As CheckBox = CType(GridMat.Rows(i).FindControl("chk"), CheckBox)
                        If (chk.Checked) Then
                            chkbox = "Y"
                        End If
                    End If

                Next
            Else
                chkbox = "Y"
            End If


            If (clsFc.InsertActual_Data_Backup_For_Billing(dr.Item("MATERIAL") & "", ViewState("EditBooking") & "", dr.Item("Text_line") & "", dr.Item("Unit") & "", dr.Item("Count") & "", dr.Item("MAT_Default") & "", dr.Item("KBETR") & "", dr.Item("KONWA") & "", dr.Item("MAT_Relation") & "", dr.Item("MAT_Compute") & "", dr.Item("MAT_Free") & "", dr.Item("data1") & "", dr.Item("data2") & "", dr.Item("data3") & "", dr.Item("data4") & "", dr.Item("New_Old") & "", chkbox, ViewState("SoldTo") & "", conn, tran) < 1) Then
                condition = False
            End If
        Next

        If (condition) Then
            clsDB.CommitTran(tran)
            'If Not ((ViewState("EditBooking").ToString.Substring(0, 1) = "B") Or (ViewState("EditBooking").ToString.Substring(0, 1) = "S")) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรียบร้อย');", True)
            'End If
        Else
        clsDB.RollBackTran(tran)
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub InsertBookingTariff_Actual_Same_Actual_Data_Backup_For_Billing()
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing

        Dim dtMat As DataTable = ViewState("dtMat")

        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)
        If (ViewState("PORT") & "" = "L") Then
            clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), "", conn, tran)
        Else
            clsFc.DeleteActual_Data_Backup_For_Billing(ViewState("EditBooking"), ViewState("SoldTo"), conn, tran)
        End If

        For Each dr As DataRow In dtMat.Rows
            If (clsFc.InsertBookingTariff_Acutal_Same_Billing(dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_Compute"), dr.Item("MAT_Free"), dr.Item("data1"), dr.Item("data2"), dr.Item("data3"), dr.Item("data4"), dr.Item("New_Old"), dr.Item("Owner") & "", conn, tran) < 1) Then
                condition = False
            End If
        Next

        If (condition) Then
            clsDB.CommitTran(tran)
            'If Not (ViewState("EditBooking").ToString.Substring(0, 1) = "B") Then
            '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรียบร้อย');", True)
            'End If
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Function ConvertMoneyToText(ByVal Money As String) As String
        Dim Digit As String = Money.Split(".")(0)
        Dim SubMoney As String
        Try
            SubMoney = Money.Split(".")(1)
        Catch ex As Exception
            SubMoney = "00"
        End Try
        Dim COuntLength As Int16 = Digit.Length
        Dim TxtMoney As String = ""
        Dim chkTen As Boolean = False
        For i As Integer = 0 To COuntLength - 1
            Dim countT As Int16 = Digit.Split(".")(0).ToString.Length
            If (COuntLength > 7) Then
                Select Case (Digit.Substring(0, 1).ToString())
                    Case "9" : TxtMoney &= "เก้า"
                    Case "8" : TxtMoney &= "แปด"
                    Case "7" : TxtMoney &= "เจ็ด"
                    Case "6" : TxtMoney &= "หก"
                    Case "5" : TxtMoney &= "ห้า"
                    Case "4" : TxtMoney &= "สี่"
                    Case "3" : TxtMoney &= "สาม"
                    Case "2" : TxtMoney &= "สอง"
                    Case "1" : TxtMoney &= "หนึ่ง"
                End Select

                Select Case (Digit.Length.ToString)
                    Case "13" : TxtMoney &= "ล้านล้าน"
                    Case "12" : TxtMoney &= "แสนล้าน"
                    Case "11" : TxtMoney &= "หมื่นล้าน"
                    Case "10" : TxtMoney &= "พันล้าน"
                    Case "9" : TxtMoney &= "ร้อยล้าน"
                    Case "8" : TxtMoney &= "สิบล้าน"
                End Select
            Else
                Select Case (Digit.Substring(0, 1).ToString())
                    Case "9" : TxtMoney &= "เก้า"
                    Case "8" : TxtMoney &= "แปด"
                    Case "7" : TxtMoney &= "เจ็ด"
                    Case "6" : TxtMoney &= "หก"
                    Case "5" : TxtMoney &= "ห้า"
                    Case "4" : TxtMoney &= "สี่"
                    Case "3" : TxtMoney &= "สาม"
                    Case "2"
                        If (countT.ToString() = "2") Then
                            TxtMoney &= "ยี่"
                        Else
                            TxtMoney &= "สอง"
                        End If

                    Case "1"
                        If (chkTen) Then
                            TxtMoney &= "เอ็ด"
                        Else
                            If (Digit.Length.ToString() <> "2") Then
                                TxtMoney &= "หนึ่ง"
                            End If
                        End If
                End Select

                Select Case (Digit.Length.ToString)
                    Case "7" : TxtMoney &= "ล้าน"
                    Case "6" : TxtMoney &= "แสน"
                    Case "5" : TxtMoney &= "หมื่น"
                    Case "4" : TxtMoney &= "พัน"
                    Case "3" : TxtMoney &= "ร้อย"
                    Case "2"
                        TxtMoney &= "สิบ"
                        chkTen = True
                    Case "1"
                        If (Digit <> 0) Then
                            TxtMoney &= "บาท"
                        End If
                End Select
            End If
            Select Case (Digit.Length.ToString())
                Case "13"
                    Digit = CInt(Digit) Mod 1000000000000
                Case "12"
                    Digit = CInt(Digit) Mod 100000000000
                Case "11"
                    Digit = CInt(Digit) Mod 10000000000
                Case "10"
                    Digit = CInt(Digit) Mod 1000000000
                Case "9"
                    Digit = CInt(Digit) Mod 100000000
                Case "8"
                    Digit = CInt(Digit) Mod 10000000
                Case "7"
                    Digit = CInt(Digit) Mod 1000000
                Case "6"
                    Digit = CInt(Digit) Mod 100000
                Case "5"
                    Digit = CInt(Digit) Mod 10000
                Case "4"
                    Digit = CInt(Digit) Mod 1000
                Case "3"
                    Digit = CInt(Digit) Mod 100
                Case "2"
                    Digit = CInt(Digit) Mod 10
                Case "1"
                    Digit = 0
                Case "0"
                    Digit = 0
            End Select
            COuntLength -= 1
        Next
        If (SubMoney <> "00") Then
            If (SubMoney.Length = 2) Then
                Select Case (SubMoney.Substring(0, 1))
                    Case "9" : TxtMoney &= "เก้าสิบ"
                    Case "8" : TxtMoney &= "แปดสิบ"
                    Case "7" : TxtMoney &= "เจ็ดสิบ"
                    Case "6" : TxtMoney &= "หกสิบ"
                    Case "5" : TxtMoney &= "ห้าสิบ"
                    Case "4" : TxtMoney &= "สี่สิบ"
                    Case "3" : TxtMoney &= "สามสิบ"
                    Case "2" : TxtMoney &= "ยี่สิบ"
                    Case "1" : TxtMoney &= "สิบ"
                End Select
                Select Case (SubMoney.Substring(1, 1))
                    Case "9" : TxtMoney &= "เก้าสตางค์"
                    Case "8" : TxtMoney &= "แปดสตางค์"
                    Case "7" : TxtMoney &= "เจ็ดสตางค์"
                    Case "6" : TxtMoney &= "หกสตางค์"
                    Case "5" : TxtMoney &= "ห้าสตางค์"
                    Case "4" : TxtMoney &= "สี่สตางค์"
                    Case "3" : TxtMoney &= "สามสตางค์"
                    Case "2" : TxtMoney &= "สองสตางค์"
                    Case "1"
                        If (SubMoney.Length = 2) Then
                            If (SubMoney.Substring(0, 1) = "0") Then
                                TxtMoney &= "หนึ่งสตางค์"
                            Else
                                TxtMoney &= "เอ็ดสตางค์"
                            End If

                        Else
                            TxtMoney &= "หนึ่งสตางค์"
                        End If
                End Select
            Else
                Select Case (SubMoney.Substring(0, 1))
                    Case "9" : TxtMoney &= "เก้าสิบสตางค์"
                    Case "8" : TxtMoney &= "แปดสิบสตางค์"
                    Case "7" : TxtMoney &= "เจ็ดสิบสตางค์"
                    Case "6" : TxtMoney &= "หกสิบสตางค์"
                    Case "5" : TxtMoney &= "ห้าสิบสตางค์"
                    Case "4" : TxtMoney &= "สี่สิบสตางค์"
                    Case "3" : TxtMoney &= "สามสิบสตางค์"
                    Case "2" : TxtMoney &= "ยี่สิบสตางค์"
                    Case "1" : TxtMoney &= "สิบสตางค์"
                End Select
            End If
        End If
        Return TxtMoney
    End Function

    Private Sub txtid_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtid.TextChanged
        AutoCompleteExtender3.ContextKey = txtid.Text.Split("-")(0)
    End Sub

    Private Sub AddBargeMaterial(ByRef dt As DataTable)
        Dim Barge As DataTable = clsGet.Get_Bas_Vessel_In(ViewState("EditBooking").ToString().Substring(1, ViewState("EditBooking").ToString.Length - 1))
        Dim ProductAmount As Double = 0.0
        Dim Truck6 As Integer = 0
        Dim Truck810 As Integer = 0
        Dim Trailer As Integer = 0
        Dim Trailer2 As Integer = 0
        Dim CountBargeVessel As Integer = 0
        If (Barge.Rows.Count > 0) Then
            For Each dr As DataRow In Barge.Rows
                If (dr.Item("Product_Amount") <> "") Then
                    ProductAmount += CDbl(dr.Item("Product_Amount"))
                    Truck6 += CInt(dr.Item("Truck6"))
                    Truck810 += CInt(dr.Item("Truck810"))
                    Trailer += CInt(dr.Item("Trailer"))
                    Trailer2 += CInt(dr.Item("Trailer2"))

                    ' e.Row.Cells(4).Text = (ts \ 60).ToString("00") & " ชั่วโมง " & (ts Mod 60).ToString("00") & " นาที"

                    Dim ts = DateDiff("n", CDate(ClassFunctionGetData.CDateT(dr.Item("StartDate"))) & " " & dr.Item("StartTime"), CDate(ClassFunctionGetData.CDateT(dr.Item("EndDate") & " " & dr.Item("EndTime"))))
                    Dim Day As Integer = 0
                    If CInt(ts \ 60) > 24 Then
                        Dim newts As Integer = CInt(ts \ 60)
                        Day = CInt(newts \ 24) + 1
                    ElseIf CInt(ts \ 60) = 24 Then
                        If (CInt(ts Mod 60)) > 0 Then
                            Day = 2
                        Else
                            Day = 1
                        End If
                    Else
                        Day = 1
                    End If
                    CountBargeVessel += Day
                End If
            Next
        End If
        If (Truck6 > 0) Then

            Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000099", ViewState("Plant"))
            If (dtMat.Tables(0).Rows.Count > 0) Then
                Dim dr As DataRow = dt.NewRow()

                dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                dr.Item("Booking_no") = ViewState("EditBooking")
                dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                dr.Item("Count") = Truck6
                dr.Item("MAT_Default") = "N"
                dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                dr.Item("MAT_Compute") = "Y"
                dr.Item("MAT_Free") = "N"
                dr.Item("data1") = ""
                dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("data3") = Truck6
                dr.Item("data4") = CDbl(Truck6 * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                dr.Item("New_Old") = "O"
                dr.Item("Owner") = ""
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If

        End If
        If (Truck810 > 0) Then
            Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000100", ViewState("Plant"))
            If dtMat.Tables(0).Rows.Count > 0 Then
                Dim dr As DataRow = dt.NewRow()

                dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                dr.Item("Booking_no") = ViewState("EditBooking")
                dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                dr.Item("Count") = Truck810
                dr.Item("MAT_Default") = "N"
                dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                dr.Item("MAT_Compute") = "Y"
                dr.Item("MAT_Free") = "N"
                dr.Item("data1") = ""
                dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("data3") = Truck810
                dr.Item("data4") = CDbl(Truck810 * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                dr.Item("New_Old") = "O"
                dr.Item("Owner") = ""
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If

        End If
        If (Trailer > 0) Then
            Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000097", ViewState("Plant"))
            If (dtMat.Tables(0).Rows.Count > 0) Then
                Dim dr As DataRow = dt.NewRow()

                dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                dr.Item("Booking_no") = ViewState("EditBooking")
                dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                dr.Item("Count") = Trailer
                dr.Item("MAT_Default") = "N"
                dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                dr.Item("MAT_Compute") = "Y"
                dr.Item("MAT_Free") = "N"
                dr.Item("data1") = ""
                dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("data3") = Trailer
                dr.Item("data4") = CDbl(Trailer * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                dr.Item("New_Old") = "O"
                dr.Item("Owner") = ""
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If

        End If
        If (Trailer2 > 0) Then
            Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000098", ViewState("Plant"))
            If (dtMat.Tables(0).Rows.Count > 0) Then
                Dim dr As DataRow = dt.NewRow()

                dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                dr.Item("Booking_no") = ViewState("EditBooking")
                dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                dr.Item("Count") = Trailer2
                dr.Item("MAT_Default") = "N"
                dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                dr.Item("MAT_Compute") = "Y"
                dr.Item("MAT_Free") = "N"
                dr.Item("data1") = ""
                dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("data3") = Trailer2
                dr.Item("data4") = CDbl(Trailer2 * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                dr.Item("New_Old") = "O"
                dr.Item("Owner") = ""
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If

        End If
        If (ProductAmount > 0) Then
            Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000260", ViewState("Plant"))
            If (dtMat.Tables(0).Rows.Count > 0) Then
                Dim dr As DataRow = dt.NewRow()

                dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                dr.Item("Booking_no") = ViewState("EditBooking")
                dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                dr.Item("Count") = ProductAmount
                dr.Item("MAT_Default") = "N"
                dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                dr.Item("MAT_Compute") = "Y"
                dr.Item("MAT_Free") = "N"
                dr.Item("data1") = ""
                dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("data3") = ProductAmount
                dr.Item("data4") = CDbl(ProductAmount * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                dr.Item("New_Old") = "O"
                dr.Item("Owner") = ""
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If

        End If
        If (CountBargeVessel > 0) Then
            Dim dtMat As DataSet = clsGet.Get_MeterailDefaultActual("2100000003", ViewState("Plant"))
            If (dtMat.Tables(0).Rows.Count > 0) Then
                Dim dr As DataRow = dt.NewRow()

                dr.Item("MATERIAL") = dtMat.Tables(0).Rows(0).Item("MATERIAL")
                dr.Item("Booking_no") = ViewState("EditBooking")
                dr.Item("Text_line") = dtMat.Tables(0).Rows(0).Item("Text_line")
                dr.Item("Unit") = dtMat.Tables(0).Rows(0).Item("Unit") & ""
                dr.Item("Count") = CountBargeVessel
                dr.Item("MAT_Default") = "N"
                dr.Item("KBETR") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("KONWA") = dtMat.Tables(0).Rows(0).Item("KONWA") & ""
                dr.Item("MAT_Relation") = dtMat.Tables(0).Rows(0).Item("Mat_Relation") & ""
                dr.Item("MAT_Compute") = "Y"
                dr.Item("MAT_Free") = "N"
                dr.Item("data1") = ""
                dr.Item("data2") = dtMat.Tables(0).Rows(0).Item("KBETR") & ""
                dr.Item("data3") = CountBargeVessel
                dr.Item("data4") = CDbl(CountBargeVessel * CDbl(dtMat.Tables(0).Rows(0).Item("KBETR"))).ToString()
                dr.Item("New_Old") = "O"
                dr.Item("Owner") = ""
                dt.Rows.Add(dr)
                dt.AcceptChanges()
            End If

        End If
    End Sub

    Private Sub AddOtherService(ByRef dt As DataTable)
        Dim Other As DataTable = clsGet.Get_OtherService_Item(ViewState("EditBooking").ToString().Substring(1, ViewState("EditBooking").ToString.Length - 1))
        For Each dot As DataRow In Other.Rows
            Dim dr As DataRow = dt.NewRow()
            dr.Item("MATERIAL") = dot.Item("MATERIAL")
            dr.Item("Booking_no") = ViewState("EditBooking")
            dr.Item("Text_line") = dot.Item("Text_line")
            dr.Item("Unit") = ""
            dr.Item("Count") = dot.Item("Amount")
            dr.Item("MAT_Default") = "N"
            dr.Item("KBETR") = dot.Item("Rate") & ""
            dr.Item("KONWA") = "THB"
            dr.Item("MAT_Relation") = ""
            dr.Item("MAT_Compute") = "Y"
            dr.Item("MAT_Free") = "N"
            dr.Item("data1") = ""
            dr.Item("data2") = dot.Item("Rate")
            dr.Item("data3") = dot.Item("Amount")
            dr.Item("data4") = CDbl(CDbl(dot.Item("Rate")) * CDbl(dot.Item("Amount"))).ToString()
            dr.Item("New_Old") = "O"
            dr.Item("Owner") = ""
            dt.Rows.Add(dr)
            dt.AcceptChanges()
        Next


    End Sub

    Public Function CreateDataset() As DataSet
        Dim ds As New DataSet
        Dim dt As New DataTable
        ds.Tables.Add(dt)
        dt.Columns.Add("id", GetType(String))
        dt.Columns.Add("MAT_NAME", GetType(String))
        dt.Columns.Add("name", GetType(String))
        dt.Columns.Add("data1", GetType(String))
        dt.Columns.Add("data2", GetType(String))
        dt.Columns.Add("data3", GetType(String))
        dt.Columns.Add("data4", GetType(String))
        ds.Tables(0).AcceptChanges()
        ds.AcceptChanges()
        Return ds
    End Function

    Private Function UpdateVessel(ByVal Vehicle As String) As Boolean
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        Dim dsConfig As DataSet = Session("Config")
        Dim Im_Veh_From As String = Vehicle
        Dim Im_Veh_To As String = ""
        Dim Date_From As String = ""
        Dim Date_To As String = ""

        Dim Ex_Subrc As Integer = 0

        Dim Veh_Table As New SAP_IPORT.ZBAPI_VEH_INPUTTable
        Dim Veh_Infor As New SAP_IPORT.ZBAPI_VEH_INFORTable
        Dim Veh_Unit As New SAP_IPORT.ZBAPI_VEH_UNITTable
        Try
            SAP_Data.Zbapi_Iport_Vehicle_Master(Date_From, Date_To, Im_Veh_From, Im_Veh_To, Ex_Subrc, Veh_Table, Veh_Infor, Veh_Unit)
        Catch ex As Exception
            ClassSAP.SAP_CLOSE(SAP_Data)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('พบความผิดพลาดในการติดต่อ SAP !!');", True)
            Exit Function
        End Try
        ClassSAP.SAP_CLOSE(SAP_Data)
        If (Veh_Unit.Count > 0) Or (Veh_Infor.Count > 0) Then
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase()
            Dim clsFc As New ClassFunction()
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Try

                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                For i As Integer = 0 To Veh_Infor.Count - 1
                    If (clsFc.UPDATEVehicle(Veh_Infor.Item(i).Vehicle, Veh_Infor.Item(i).Veh_Text, Veh_Infor.Item(i).Owner, Veh_Infor.Item(i).Reg_Cntry, Veh_Infor.Item(i).Veh_Type, Veh_Infor.Item(i).Veh_Length, Veh_Infor.Item(i).Veh_Width, Veh_Infor.Item(i).Veh_Height, Veh_Infor.Item(i).Draft, Veh_Infor.Item(i).Dim_Uom, Veh_Infor.Item(i).Veh_Unlwgt, Veh_Infor.Item(i).Veh_Unlwgt_C, Veh_Infor.Item(i).Veh_Maxwgt, Veh_Infor.Item(i).Veh_Maxwgt_C, Veh_Infor.Item(i).Wgt_Uom, Veh_Infor.Item(i).Veh_Maxvol, Veh_Infor.Item(i).Veh_Maxvol_C, Veh_Infor.Item(i).Vol_Uom, Veh_Infor.Item(i).Stcmnr, Veh_Infor.Item(i).Veh_Nrtus, conn, tran) = 0) Then
                        If (clsFc.InsertVehicle(Veh_Infor.Item(i).Vehicle, Veh_Infor.Item(i).Veh_Text, Veh_Infor.Item(i).Owner, Veh_Infor.Item(i).Reg_Cntry, Veh_Infor.Item(i).Veh_Type, Veh_Infor.Item(i).Veh_Length, Veh_Infor.Item(i).Veh_Width, Veh_Infor.Item(i).Veh_Height, Veh_Infor.Item(i).Draft, Veh_Infor.Item(i).Dim_Uom, Veh_Infor.Item(i).Veh_Unlwgt, Veh_Infor.Item(i).Veh_Unlwgt_C, Veh_Infor.Item(i).Veh_Maxwgt, Veh_Infor.Item(i).Veh_Maxwgt_C, Veh_Infor.Item(i).Wgt_Uom, Veh_Infor.Item(i).Veh_Maxvol, Veh_Infor.Item(i).Veh_Maxvol_C, Veh_Infor.Item(i).Vol_Uom, Veh_Infor.Item(i).Stcmnr, Veh_Infor.Item(i).Veh_Nrtus, conn, tran) < 1) Then
                            condition = False
                        End If
                    End If
                Next
                For i As Integer = 0 To Veh_Unit.Count - 1
                    If (clsFc.UPDATEVehicle_infor(Veh_Unit.Item(i).Vehicle, Veh_Unit.Item(i).Tu_Type, Veh_Unit.Item(i).Tu_Class, Veh_Unit.Item(i).Tu_Mode, Veh_Unit.Item(i).Tu_Length, Veh_Unit.Item(i).Tu_Width, Veh_Unit.Item(i).Tu_Height, Veh_Unit.Item(i).Dim_Uom, Veh_Unit.Item(i).Tu_Unlwgt, Veh_Unit.Item(i).Tu_Unlwgt_C, Veh_Unit.Item(i).Tu_Maxwgt, Veh_Unit.Item(i).Tu_Maxwgt_C, Veh_Unit.Item(i).Wgt_Uom, Veh_Unit.Item(i).Tu_Maxvol, Veh_Unit.Item(i).Tu_Maxvol_C, Veh_Unit.Item(i).Vol_Uom, conn, tran) = 0) Then
                        If (clsFc.InsertVehicle_infor(Veh_Unit.Item(i).Vehicle, Veh_Unit.Item(i).Tu_Type, Veh_Unit.Item(i).Tu_Class, Veh_Unit.Item(i).Tu_Mode, Veh_Unit.Item(i).Tu_Length, Veh_Unit.Item(i).Tu_Width, Veh_Unit.Item(i).Tu_Height, Veh_Unit.Item(i).Dim_Uom, Veh_Unit.Item(i).Tu_Unlwgt, Veh_Unit.Item(i).Tu_Unlwgt_C, Veh_Unit.Item(i).Tu_Maxwgt, Veh_Unit.Item(i).Tu_Maxwgt_C, Veh_Unit.Item(i).Wgt_Uom, Veh_Unit.Item(i).Tu_Maxvol, Veh_Unit.Item(i).Tu_Maxvol_C, Veh_Unit.Item(i).Vol_Uom, conn, tran) < 1) Then
                            condition = False
                        End If
                    End If

                Next
                If (Date_To <> "") Then
                    If (clsFc.UpdateVehicle_Date(Date_To, conn, tran) < 1) Then
                        condition = False
                    End If
                End If

                If (condition) Then
                    clsDB.CommitTran(tran)
                    conn.Close()
                    Application.UnLock()
                    Veh_Infor.Clear()
                    Veh_Unit.Clear()
                    conn.Dispose()

                    Return True
                Else
                    clsDB.RollBackTran(tran)
                    conn.Close()
                    Application.UnLock()
                    Veh_Infor.Clear()
                    Veh_Unit.Clear()
                    conn.Dispose()
                    Return False
                End If
            Catch ex As Exception
                clsDB.RollBackTran(tran)
                conn.Close()
                Application.UnLock()
                Veh_Infor.Clear()
                Veh_Unit.Clear()
                conn.Dispose()
                Return False
            End Try

        Else
            Return True
        End If
    End Function

    Private Sub GetValueVessel(ByVal Vessel_Code As String, ByRef GRT As String, ByRef LOA As String, ByRef DWT As String, ByRef Draft As String)
        If (UpdateVessel(Vessel_Code)) Then
            'Update Vessel
            Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(Vessel_Code)

            'Bind Data VEHICLE Detail
            LOA = (CDbl(ds.Rows(0).Item("VEH_LENGTH")) * 3.281).ToString("############0.00")
            DWT = ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim()
            Draft = (CDbl(ds.Rows(0).Item("DRAFT")) * 3.281).ToString("############0.00")
            GRT = ds.Rows(0).Item("STCMNR").ToString().Replace("GRT", "").Replace("=", "").Replace("MT", "")
        End If
    End Sub

    Private Function ComputeMoney(ByVal MATERIAL As String, ByVal GRT As String, ByVal LOA As String, ByVal DWT As String, ByVal Draft As String, ByVal ProductValue As String, ByVal Customer_no As String, ByVal PORT As String, ByVal _StandardTime As String, ByVal Day As String, ByVal ValueItem As String, ByVal Destinatin As String, ByVal VesselNational As String) As DataTable
        Dim dtRelation As DataTable = clsGet.Get_MeterailRelation(MATERIAL)
        Dim ds As New DataSet
        ds = CreateDataset()
        If (dtRelation.Rows.Count > 0) Then
            Dim Value As Double = 0.0
            Select Case dtRelation.Rows(0).Item("Relation")
                Case "01" 'สูตรคำนวนน้ำหนักเรือ GRT 
                    Value = GRT
                Case "02" 'L.O.A.
                    Value = LOA
                Case "03" 'DWT
                    Value = DWT
                Case "04" 'Draft
                    Value = Draft
                Case "05" 'Product
                    Value = ProductValue
                Case "06"
                    Value = 0.0
            End Select
            Dim conditioncheck As Boolean = False
            For Each drR As DataRow In dtRelation.Rows
                If (drR.Item("Vessel_national") = "A") Then
                    If (drR.Item("Vessel_Destination") = "A") Then
                        conditioncheck = True
                    ElseIf (drR.Item("Vessel_Destination") = "I") Then
                        If (Destinatin = "I") Then
                            conditioncheck = True
                        Else
                            conditioncheck = False
                        End If
                    ElseIf (drR.Item("Vessel_Destination") = "O") Then
                        If (Destinatin = "O") Then
                            conditioncheck = True
                        Else
                            conditioncheck = False
                        End If
                    End If
                ElseIf (drR.Item("Vessel_national") = "T") Then
                    If (VesselNational = "T") Then
                        If (drR.Item("Vessel_Destination") = "A") Then
                            conditioncheck = True
                        ElseIf (drR.Item("Vessel_Destination") = "I") Then
                            If (Destinatin = "I") Then
                                conditioncheck = True
                            Else
                                conditioncheck = False
                            End If
                        ElseIf (drR.Item("Vessel_Destination") = "O") Then
                            If (Destinatin = "O") Then
                                conditioncheck = True
                            Else
                                conditioncheck = False
                            End If
                        End If
                    Else
                        conditioncheck = False
                    End If
                ElseIf (drR.Item("Vessel_national") = "O") Then
                    If (VesselNational = "O") Then
                        If (drR.Item("Vessel_Destination") = "A") Then
                            conditioncheck = True
                        ElseIf (drR.Item("Vessel_Destination") = "I") Then
                            If (Destinatin = "I") Then
                                conditioncheck = True
                            Else
                                conditioncheck = False
                            End If
                        ElseIf (drR.Item("Vessel_Destination") = "O") Then
                            If (Destinatin = "O") Then
                                conditioncheck = True
                            Else
                                conditioncheck = False
                            End If
                        End If
                    Else
                        conditioncheck = False
                    End If
                End If
                If (conditioncheck) Then
                    'ทำการเปรียบเทียบช่วงน่ำหนักเรือ
                    If (drR.Item("Compute_Between") & "" = "A") Then
                        'แบบแรกตกช่วงคิด
                        If ((CDbl(drR("Point_Start")) <= Value) And (CDbl(drR("Point_End")) >= Value)) Then
                            'Rate ตกในช่วง
                            Dim rate As String = drR.Item("Mat_Rate")
                            If (dtRelation.Rows(0).Item("Customer_no") & "" <> "") Then
                                Dim Cus() As String = dtRelation.Rows(0).Item("Customer_no").ToString().Split(",")
                                For i As Integer = 0 To Cus.Length - 1
                                    If (Cus(i).ToString = Customer_no) Then
                                        rate = dtRelation.Rows(0).Item("Customer_Rate").ToString().Split(",")(i)
                                        Exit For
                                    End If
                                Next
                            End If
                            Dim drNew As DataRow = ds.Tables(0).NewRow()
                            Try
                                drNew.Item("id") = CInt(drR.Item("Meterial")).ToString()
                            Catch ex As Exception
                                drNew.Item("id") = drR.Item("Meterial").ToString()
                            End Try

                            drNew.Item("name") = drR.Item("Mat_Name")
                            drNew.Item("MAT_NAME") = ""  'ไม่ได้แสดง
                            If (CInt(Value).ToString() = "0") Then
                                Value = 1.0
                                drNew.Item("data1") = ""
                            Else
                                drNew.Item("data1") = Value
                            End If
                            Try
                                Try
                                    drNew.Item("data2") = CDbl(rate).ToString("#################0.00")
                                Catch ex As Exception
                                    drNew.Item("data2") = rate
                                End Try

                                Dim newValue As Double = 0
                                If (drR.Item("Point_Unit") = "0") Then
                                    newValue = 1
                                Else
                                    If (drNew.Item("id") = "2100000268") Then
                                        newValue = (Value / CDbl(drR.Item("Point_Unit"))).ToString("###################0.00")
                                    Else
                                        newValue = (Value / CDbl(drR.Item("Point_Unit"))).ToString("###################0.000")
                                    End If

                                End If
                                Dim StardardTime As Double = 0.0
                                If (drR("data3") = "S") Or (drR("data3") = "C") Then
                                    StardardTime = CDbl(_StandardTime)
                                End If
                                If (drR("Data3") = "N") Then
                                    drNew.Item("data3") = ""
                                    drNew.Item("data4") = (newValue * CDbl(rate)).ToString("###############0.00")
                                ElseIf (drR("Data3") = "S") Then
                                    Session("Lay_Time") = StardardTime
                                    drNew.Item("data3") = StardardTime
                                    drNew.Item("data4") = (CDbl((newValue * CDbl(rate)).ToString("###################.00")) * StardardTime).ToString("###############0.00")
                                Else
                                    If (drR.Item("Compute_Count") & "" = "") Then
                                        If (drR.Item("Compute_C") & "" = "D") Then
                                            drNew.Item("data3") = Day
                                        Else
                                            If MATERIAL = "WP" Or MATERIAL = "000000002100000187" Or MATERIAL = "2100000187" Then
                                                If (ValueItem <> "") Then
                                                    drNew.Item("data3") = ValueItem
                                                End If
                                            Else
                                                If (Value Mod CDbl(drR.Item("Point_Unit"))) <> 0 Then
                                                    drNew.Item("data3") = (CDbl(Value \ CDbl(drR.Item("Point_Unit"))) + 1).ToString()
                                                Else
                                                    drNew.Item("data3") = CDbl(Value \ CDbl(drR.Item("Point_Unit"))).ToString()
                                                End If
                                            End If

                                        End If
                                    Else
                                        If (ValueItem = "") Then
                                            drNew.Item("data3") = drR.Item("Compute_Count")
                                        Else
                                            drNew.Item("data3") = ValueItem
                                        End If
                                    End If
                                    Try
                                        If (CInt(drR.Item("Meterial")).ToString() = "2100000099") Or (CInt(drR.Item("Meterial")).ToString() = "2100000100") Or (CInt(drR.Item("Meterial")).ToString() = "2100000098") Or (CInt(drR.Item("Meterial")).ToString() = "2100000097") Or (CInt(drR.Item("Meterial")).ToString() = "2100000187") Then
                                            drNew.Item("data3") = ValueItem
                                        End If
                                    Catch ex As Exception

                                    End Try


                                    drNew.Item("data4") = (CDbl(rate) * CDbl(drNew.Item("data3"))).ToString("###############0.00")
                                End If
                                If (drR.Item("LowRate") & "" = "") Then
                                    drR.Item("LowRate") = "0"
                                End If
                                If (CDbl(drR.Item("LowRate")) > 0.0) Then
                                    If (CDbl(drR.Item("LowRate")) > CDbl(drNew.Item("data4"))) Then
                                        'ราคาต่ำกว่า ราคาขั้นต่ำ
                                        If (drNew.Item("data3") = "") Then
                                            drNew.Item("data2") = drR.Item("LowRate")
                                            drNew.Item("data4") = drR.Item("LowRate")
                                        Else
                                            drNew.Item("data4") = drR.Item("LowRate")
                                            drNew.Item("data2") = CDbl(drR.Item("LowRate") / drNew.Item("data3")).ToString("################0.00")
                                        End If
                                    End If
                                End If
                            Catch ex As Exception
                                '((LOA-5)*Draft)+10%
                                If (drR.Item("LowRate") & "" = "") Then
                                    drR.Item("LowRate") = "0"
                                End If
                                Dim LoACompute As Double = ((LOA - 5.0) * Draft) + ((((LOA - 5.0) * Draft) * 10) / 100).ToString("##################0.00")
                                If (CDbl(drR.Item("LowRate")) > LoACompute) Then
                                    drNew.Item("data2") = drR.Item("LowRate")
                                    drNew.Item("data3") = "1"
                                    drNew.Item("data4") = drR.Item("LowRate")
                                Else
                                    drNew.Item("data2") = LoACompute.ToString()
                                    drNew.Item("data3") = "1"
                                    drNew.Item("data4") = LoACompute.ToString()
                                End If
                                If (CDbl(ValueItem) > 1) Then
                                    drNew.Item("data3") = ValueItem
                                    Dim Digit As Double = CDbl(ValueItem) - 1.0
                                    drNew.Item("data4") = (CDbl(drNew.Item("data4")) + (CDbl(drNew.Item("data4")) * Digit)).ToString("####################0.00")
                                End If
                            End Try
                            ds.Tables(0).Rows.Add(drNew)
                            ds.Tables(0).AcceptChanges()
                            Exit For
                        End If
                    Else
                        'แบบสองผ่านช่วงไหนคิดหมด
                        If ((CDbl(drR("Point_Start")) <= Value)) Then
                            'Rate ตกในช่วง
                            Dim drNew As DataRow = ds.Tables(0).NewRow()
                            drNew.Item("id") = CInt(drR.Item("Meterial")).ToString()
                            drNew.Item("name") = drR.Item("Mat_Name")
                            drNew.Item("MAT_NAME") = "" 'ไม่ม่ชื่อ
                            Dim Nvalue As Double = 0
                            If (Value > drR("Point_End")) Then
                                Nvalue = drR("Point_End") - CDbl(drR("Point_Start"))
                            Else
                                Nvalue = Value - CDbl(drR("Point_Start"))
                            End If
                            Dim rate As String = drR.Item("Mat_Rate")
                            If (dtRelation.Rows(0).Item("Customer_no") & "" <> "") Then
                                Dim Cus() As String = dtRelation.Rows(0).Item("Customer_no").ToString().Split(",")
                                For i As Integer = 0 To Cus.Length - 1
                                    If (Cus(i).ToString = Customer_no) Then
                                        rate = dtRelation.Rows(0).Item("Customer_Rate").ToString().Split(",")(i)
                                        Exit For
                                    End If
                                Next
                            End If
                            drNew.Item("data1") = Nvalue
                            Try
                                drNew.Item("data2") = CDbl(rate).ToString("###################0.00")
                            Catch ex As Exception
                                drNew.Item("data2") = rate
                            End Try


                            Dim newValue As Double = 0
                            If (drR.Item("Point_Unit") = "0") Then
                                newValue = 1
                            Else
                                newValue = (Nvalue / CDbl(drR.Item("Point_Unit"))).ToString("###################0.00")
                            End If
                            Dim StardardTime As Double = 0.0
                            If (drR("data3") = "S") Or (drR("data3") = "C") Then
                                StardardTime = _StandardTime
                            End If
                            If (drR("Data3") = "N") Then
                                drNew.Item("data3") = ""
                                drNew.Item("data4") = (newValue * CDbl(rate)).ToString("###############0.00")

                            ElseIf (drR("Data3") = "S") Then
                                'ทำการคำนวณหา Stardard Time
                                'If (StardardTime = 0) Then
                                '    StardardTime = 1
                                'End If
                                Session("Lay_Time") = StardardTime
                                drNew.Item("data3") = StardardTime
                                drNew.Item("data4") = (CDbl((newValue * CDbl(rate)).ToString("#################0.00")) * StardardTime).ToString("###############0.00")
                            Else
                                If (drR.Item("Compute_Count") & "" = "") Then
                                    If (drR.Item("Compute_C") & "" = "D") Then
                                        drNew.Item("data3") = Day
                                    Else
                                        If (Value Mod CDbl(drR.Item("Point_Unit"))) <> 0 Then
                                            drNew.Item("data3") = (CDbl(Value \ CDbl(drR.Item("Point_Unit"))) + 1).ToString()
                                        Else
                                            drNew.Item("data3") = CDbl(Value \ CDbl(drR.Item("Point_Unit"))).ToString()
                                        End If
                                    End If
                                Else
                                    If (ValueItem = "") Then
                                        drNew.Item("data3") = drR.Item("Compute_Count")
                                    Else
                                        drNew.Item("data3") = ValueItem
                                    End If

                                End If

                                drNew.Item("data4") = (CDbl(rate) * CDbl(drNew.Item("data3"))).ToString("###############0.00")
                            End If
                            If (drR.Item("LowRate") & "" = "") Then
                                drR.Item("LowRate") = "0"
                            End If
                            If (CDbl(drR.Item("LowRate")) > 0.0) Then
                                If (CDbl(drR.Item("LowRate")) > CDbl(drNew.Item("data4"))) Then
                                    'ราคาต่ำกว่า ราคาขั้นต่ำ
                                    If (drNew.Item("data3") = "") Then
                                        drNew.Item("data2") = drR.Item("LowRate")
                                        drNew.Item("data4") = drR.Item("LowRate")
                                    Else
                                        drNew.Item("data4") = drR.Item("LowRate")
                                        drNew.Item("data2") = CDbl(drR.Item("LowRate") / drNew.Item("data3")).ToString("################0.00")
                                    End If
                                End If
                            End If

                            ds.Tables(0).Rows.Add(drNew)
                            ds.Tables(0).AcceptChanges()
                            Exit For
                        End If
                    End If
                End If
            Next
        Else
            'ไม่พบข้อมูลการผูกสูตร
            Dim Plant As String = "1104"
            If (PORT = "L") Then
                Plant = "1103"
            End If
            dtRelation = clsGet.Get_SubMeterail(MATERIAL)
            If (dtRelation.Rows.Count > 0) Then
                For Each dm As DataRow In dtRelation.Rows
                    If (Plant = dm.Item("WERKS")) Then
                        Dim drNew As DataRow = ds.Tables(0).NewRow()
                        Dim id As String = ""
                        Try
                            id = CInt(MATERIAL).ToString()
                        Catch ex As Exception
                            id = MATERIAL
                        End Try
                        drNew.Item("id") = id
                        drNew.Item("name") = ""
                        drNew.Item("MAT_NAME") = ""
                        drNew.Item("data1") = ""
                        drNew.Item("data2") = dm.Item("KBETR")
                        drNew.Item("data3") = ValueItem


                        drNew.Item("data4") = CDbl(dm.Item("KBETR") * CDbl(ValueItem)).ToString("###############0.00")
                        ds.Tables(0).Rows.Add(drNew)
                        ds.Tables(0).AcceptChanges()
                    End If
                Next
            End If
        End If
        Return ds.Tables(0)
    End Function

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        ViewState("Booking_OLD") = ""
        Dim status As String = ""
        If (ddlStatus.SelectedValue = "0") Then
            status = "'OA','FN'"
        ElseIf (ddlStatus.SelectedValue = "1") Then
            status = "'FN'"
        Else
            status = "'OA'"
        End If
        Dim ds As DataSet = clsGet.Get_BookingMarketing(txtBooking_no.Text, status, True, txtShipName.Text, ddlPORT.SelectedValue, txtAgent.Text, ddlTypeBOoking.SelectedValue, "", "", "")

        If (txtDateFromM.Text <> "") Then
            Dim c As Integer = 0
            Dim dtTemp As DataTable = ds.Tables(0).Copy
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Dim dtLogin As DataTable = clsGet.Get_Booking_LogSheet_In(ds.Tables(0).Rows(i).Item("Booking_no"))
                Try
                    If (dtLogin.Rows(0).Item("Berthing_Date") <> txtDateFromM.Text) Then
                        dtTemp.Rows(i - c).Delete()
                        dtTemp.AcceptChanges()
                        c += 1
                    End If
                Catch ex As Exception
                    dtTemp.Rows(i - c).Delete()
                    dtTemp.AcceptChanges()
                    c += 1
                End Try
            Next
            ds.Tables.Clear()
            ds.Tables.Add(dtTemp.Copy)
            ds.AcceptChanges()
        End If
        If (ds.Tables(0).Rows.Count > 0) Then
            ViewState("Operation") = ds
            gridItem.DataSource = ViewState("Operation")
            gridItem.DataBind()
            lbAlert.Text = ""
        Else
            gridItem.DataSource = Nothing
            gridItem.DataBind()
            lbAlert.Text = "ไม่พบรายการ Booking"
        End If
    End Sub


    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Public Sub chk_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        ' If (ViewState("PORT") & "" = "B") Then
        lbNet.Text = "0"

        For i As Integer = 0 To GridMat.Rows.Count - 1
            Dim chk As CheckBox = CType(GridMat.Rows(i).FindControl("chk"), CheckBox)
            If Not ((ViewState("EditBooking").ToString.Substring(0, 1) = "B") Or (ViewState("EditBooking").ToString.Substring(0, 1) = "S")) Then
                If (chk.Checked) Then
                    Dim txtData4 As TextBox = CType(GridMat.Rows(i).FindControl("txtData4"), TextBox)
                    lbNet.Text = FormatNumber(CDbl(lbNet.Text) + CDbl(txtData4.Text), 2)
                End If
            Else
                chk.Checked = True
                Dim txtData4 As TextBox = CType(GridMat.Rows(i).FindControl("txtData4"), TextBox)
                lbNet.Text = FormatNumber(CDbl(lbNet.Text) + CDbl(txtData4.Text), 2)
            End If

        Next
        'End If
    End Sub

    Private Function GenBody(ByVal str As String) As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td align='left'><font class='White-Style' font-weight:bold style='color:#000000'>" & str & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"

        Return HTML
    End Function

    Private Function GetPath() As String
        Dim path As String = CreateReport()
        If (path <> "") Then
            Dim str() As String = Split(path, "WriteReport")
            path = Server.MapPath("..") & "/WriteReport" & str(str.Length - 1)
        End If
        Return path
    End Function

    Private Function SendMail(ByVal Booking As String, ByVal Body As String) As Boolean
        Dim test As String = clsFc.sendmail(clsGet.Get_EmailForSendAgent(Booking), "", "iPORT", Body, GetPath())
        If (test <> "") Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnTariff_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTariff.Click
        Session("MAT_USE") = Nothing
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_framePopup').src = '../FormPopup/FrmTariff_Popup.aspx';", True)
        ModalPopupExtender1.Show()
    End Sub
End Class